Java switch语句要求输入两次

时间:2012-01-29 21:08:55

标签: java loops input switch-statement

我不明白这个switch语句是怎么回事。我试图让用户输入l更少,m更多。如果他们放的少,那么它只会在'l'情况下进行计算。但这似乎要求用户输入来自'l'的情况并转到'm'的情况并再次询问,因此用户必须输入l l for less和m m for more而不是只输入一次。

尝试使用switch或者编写代码的方式有问题吗?

        while (choice == console.next().charAt(0));

EDIT: Figured out this was asking for input instead so it kept asking twice each time.

2 个答案:

答案 0 :(得分:1)

你要求选择两次,一次是在案例陈述中:

        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));

解决方案:仅输入一次

答案 1 :(得分:1)

  1. 您要求选择两次(在案件内和在条件下)。

  2. 再一次重申这一点:

    while (choice == console.next().charAt(0))
    
  3. 它不仅仅是要求输入一次。当用户改变主意时,它也会打破循环......

    您应该从while条件中删除控制台读数,并将其更改为:

    while(choice != 'y');