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
请求两次输入的Java switch语句_Java_Loops_Input_Switch Statement - Fatal编程技术网

请求两次输入的Java switch语句

请求两次输入的Java switch语句,java,loops,input,switch-statement,Java,Loops,Input,Switch Statement,我不明白这个switch语句是怎么回事。我试图让用户输入l表示更少,m表示更多。如果他们投入较少,那么它只会在“l”情况下进行计算。但这似乎是在要求用户从“l”案例输入,然后转到“m”案例,然后再次询问,因此用户必须输入l以获得更少,m以获得更多,而不是仅输入一次 这是尝试使用switch的问题还是我编写代码的方式的问题 while (choice == console.next().charAt(0)); EDIT: Figured out this was asking f

我不明白这个switch语句是怎么回事。我试图让用户输入l表示更少,m表示更多。如果他们投入较少,那么它只会在“l”情况下进行计算。但这似乎是在要求用户从“l”案例输入,然后转到“m”案例,然后再次询问,因此用户必须输入l以获得更少,m以获得更多,而不是仅输入一次

这是尝试使用switch的问题还是我编写代码的方式的问题

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

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

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

        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));
解决方案:只获取一次输入

  • 您要求选择两次(在机箱内和在while条件下)

  • 再次重新思考这个while条件:

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

    您应该从while条件中删除控制台读数,并将其更改为类似以下内容:

    while(choice != 'y');
    

    好的,我想这意味着它在选择输入时会继续运行,但实际上它又在选择输入。谢谢你,我能改变它。是的,这正是我所做的修复它。当时我认为我正在将条件设置为字面意义上的“在请求输入时执行此操作”。