我不明白这个 switch 语句是怎么回事。我试图让用户输入 l 表示更少,m 表示更多。如果他们输入的较少,那么它只会在“l”情况下进行计算。但这似乎要求用户从“l”情况输入,然后转到“m”情况并再次询问,因此用户必须输入 l l 表示更少,mm 表示更多,而不是只输入一次。
这是尝试使用 switch 的问题还是我编写代码的方式有问题?
while (choice == console.next().charAt(0));
EDIT: Figured out this was asking for input instead so it kept asking twice each time.
最佳答案
您要求选择两次,一次是在 case 语句中:
case 'l': //If it is lower then 499 becomes the upperBound
upperBound = nextGuess;
tries++;
nextGuess = ( (lowerBound + upperBound)/2 );
System.out.println("Is it " + nextGuess +
"? \n\t Enter y if it is, l if it is less, or m if it is more.");
// **** here ****
choice = console.next().charAt(0);
System.out.println("LOWER");
break;
再次在 while 条件下,即
while (choice == console.next().charAt(0));
解决方案:仅获取输入一次。
关于Java switch 语句要求输入两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9056817/