Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 为什么循环两次?为什么不';这些方法不能运行吗?_Loops_While Loop_User Input - Fatal编程技术网

Loops 为什么循环两次?为什么不';这些方法不能运行吗?

Loops 为什么循环两次?为什么不';这些方法不能运行吗?,loops,while-loop,user-input,Loops,While Loop,User Input,上面的代码似乎运行了两次,在扫描器再次请求用户输入之前,x减少了两次 public static void main(String[] args) { Scanner userInput = new Scanner(System.in); int x = 20; String choice = ""; while(x!=0) { System.out.println("What would you like to do?

上面的代码似乎运行了两次,在扫描器再次请求用户输入之前,x减少了两次

public static void main(String[] args) {

    Scanner userInput = new Scanner(System.in);
    int x = 20;
    String choice = "";
            while(x!=0) {

            System.out.println("What would you like to do? Enter help for commands.");
            choice = userInput.next().toLowerCase();

            if(choice.equals("go right")) method(); 
            if(choice.equals("go left")) method();
            if(choice.equals("go forwards")) method();
            if(choice.equals("go backwards")) method();
            if(choice.equals("help")) System.out.println("I can print!");

            x--;
            System.out.println("Value of x: " + x);

        }
}

此外,当从if语句调用时,该方法不会运行,但打印语句会运行。

您的方法不会被调用,因为
userInput.next()
将只返回下一个单词(即,直到有空格为止)。您应该查看
.nextLine()
.usedimiter()
以更改此行为并返回整行

这也解释了为什么x会减少两次——如果您键入“向右”,这将计为两个独立的
.next()
s

  • 必须将
    static
    添加到
    method
    ,因为现在它是一个实例方法,不能从像
    main
    这样的静态函数调用
  • 不要选中
    x!=0
    它可能工作,但在一个复杂的循环中,
    x
    可以减少一次以上,它可能会超过0,变成负数,并且永远不会结束循环。改为选中
    x>0
  • 如果需要在循环结束时递增/递减循环控制变量,则在时,使用
    代替

  • 我全心全意地爱你。
     public void method(){
          System.out.println("methoding");
    }