Loops 为什么循环两次?为什么不';这些方法不能运行吗?
上面的代码似乎运行了两次,在扫描器再次请求用户输入之前,x减少了两次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?
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");
}