如何执行ArrayList?

问题描述 投票:0回答:1

我有一个可以通过用户输入进行控制的雀科机器人。所以我创建了一个ArrayList来存储用户输入。因此,现在我有一个情况,如果用户输入T,则程序应反向执行数组中的输入。

    case "forward":
    case "F" :
    case "f" :

        System.out.println("you selected forward");
        while(input == "f");

           System.out.println("Please enter duration (seconds)");
            int duration1 = scanner.nextInt();

           System.out.println("Please enter speed");
             int speed1 = scanner.nextInt();

            if((speed1>=0 && speed1<201) && (duration1>=0 && duration1<7))
                myFinch.setWheelVelocities(speed1, speed1, duration1*1000);

            RepeatCommands1.add(duration1);
            RepeatCommands1.add(speed1);

            System.out.println(z);
            //else
                //System.out.println("invalid values");
        break;

    case "retrace" :        
    case "T":

        System.out.print(Commandname);
        Commandname.remove("T");

        System.out.print(RepeatCommands1);

        CommandArray.addAll(RepeatCommands1);
        Collections.reverse(CommandArray);

        System.out.println(CommandArray);

        System.out.println(z);
        break;
java eclipse arraylist switch-statement finch
1个回答
0
投票
  1. 为什么第5行上有while(input == "f");?它要做什么?也许您想将其放在switch()语句之前?请注意,在此循环中没有中断条件或语句,如果您输入了它,则它是无限的,由于使用了错误的运算符,您可能不会输入。
  2. 使用String对象时,使用==运算符很不好,因为它比较对象引用而不是它们的“实际值”。改为使用equals()方法,如下所示:while (input.equals("f")) { ... }在String下,您可以阅读更多here,并且有很好的示例here
  3. 旁注:使用Collections.reverse()(请阅读here时,它说:

    此方法在线性时间内运行。

    因此,如果您仅使用ArrayList<String>来存储命令,则可以尝试使用另一个Collection:Stack<String>,只是在O(1)的时间复杂度上使用push()/pop(),而不是反转O(n )。如果需要,请参见示例here

© www.soinside.com 2019 - 2024. All rights reserved.