有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

循环Java开关语句,请求输入两次

我不明白这个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.

共 (2) 个答案

  1. # 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));
    

    解决方案:只获取一次输入

  2. # 2 楼答案

    1. 你要求两次选择(在箱子内和在while条件下)

    2. 再次重新考虑一下这种情况:

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

    这不仅仅是再次要求投入。当用户改变主意时,它也会打破循环

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

    while(choice != 'y');