代码之家  ›  专栏  ›  技术社区  ›  Joe

while循环不执行中的代码

  •  0
  • Joe  · 技术社区  · 15 年前

    我在玩Java,想做一个简单的while循环,直到用户按下为止。 控制 + Z .

    我有这样的东西:

    public static void main(String[] args) {
    
        //declare vars
        boolean isEvenResult;
        int num;
    
        //create objects
        Scanner input = new Scanner(System.in);
        EvenTester app = new EvenTester();
    
        //input user number
        System.out.print("Please enter a number: ");
        num = input.nextInt();
    
        while() {
    
            //call methods
            isEvenResult = app.isEven(num);
    
            if(isEvenResult) {
                System.out.printf("%d is even", num);
            } else {
                System.out.printf("%d is odd", num);
            }
    
        }//end while loop
    
    }//end main
    

    我试过 while( input.hasNext() ) { ... 但是while循环中的代码不会执行。

    7 回复  |  直到 9 年前
        1
  •  3
  •   True Soft    15 年前
    //input user number
    System.out.print("Please enter a number: ");
    
    do {
        try {
            num = input.nextInt();
        } catch (Exception e) {
            break;
        }
        // call methods
        isEvenResult = app.isEven(num);
    
        if (isEvenResult) {
            System.out.printf("%d is even", num);
        } else {
            System.out.printf("%d is odd", num);
        }
    } while (true);
    

    当用户写入非数字的内容时,循环将中断。

        2
  •  1
  •   Gandalf    15 年前

    虽然(嗯)!=“z”

    尽管您希望有一个“z”,为什么要做input.getint()?

    您可能想查看 Console 课也一样。

        3
  •  1
  •   JRL    15 年前

    如果要循环直到用户必须通过ctrl+z强制中断,那么只需执行 while(true) . 但你想要你的 nextInt( )在循环中,也可能是提示语句。

        4
  •  1
  •   Carl Smotricz    15 年前

    TrueSoft的解决方案已经过时了。它可能对asker不起作用的原因有点超出了程序的范围。

    这个程序适用于我:我在Linux下运行它,在一行中输入ctrl-d作为第一件事。ctrl-d是Linux的文件尾,与ctrl-z用于Windows的方式相同。程序完全停止运行。

    Windows控制台(黑色的DOS框,不管你怎么称呼它)有一个褶皱:它逐行读取输入。在读取行之前,它不会看到ctrl-z,因此在看到ctrl-z之前,它需要一个回车键。

    我不愿意为了尝试这个而启动Windows,但是我猜ctrl-z后面跟着enter键(就像在数字输入之后一样)会导致程序干净地停止。

    有一种系统的方法使Java程序按字符进行工作,这样您就可以直接处理任何字符,并立即响应CTRL Z。但这是高级的东西,不属于这样的简单编程练习。我认为ctrl-z/enter是一种可以接受的结束程序的方法。

        5
  •  0
  •   ChadNC    15 年前

    你需要实施 KeyBindings . 然后,您可以根据按下的键决定退出。

        6
  •  0
  •   Kushal Paudyal    15 年前

    您在循环外部执行输入,它将只运行一次。

    System.out.print("Please enter a number: ");
    num = input.nextInt();
    

    把上面的代码放到循环中。

    因为您在循环中有一个系统,所以您还将了解控件是否进入了循环,显然它应该这样做。

    另外,试试看

    while(true)
    

    我想知道,单独使用()是否有效。

        7
  •  0
  •   Jim    12 年前

    这看起来像是Deitel的《Java如何编程,第九版》中的练习6.16。

    实际上,ctrl-z字符确实在Windows平台上结束输入,就像ctrl-d在大多数UNIX或Linux平台上结束输入一样。

    此外,在程序的构造中也存在逻辑错误,表明扫描器方法和字节流中的系统(即控制台的标准输入)不被很好地理解。

    在您发布的程序中,声明:

        num = input.nextInt(); 
    

    无条件执行。它将阻止执行,直到接收到某种输入。如果输入不是整数,它将引发异常。如果接收到的输入是整数,那么num将被分配整数值,输入流(input)中的整数将从输入流中丢弃。根据用户在点击结束输入行并将其放入系统的回车键之前输入的内容,输入行上可能还有剩余的内容,在扫描程序正在扫描的字节流中。

    如果不将input.hasNext()放入while语句的测试条件中,而是将程序保留为已写入状态,则在nextint()处理整数后的输入流中有更多输入之前,它将一直阻塞。

    一些答案建议使用键绑定作为解决方案。虽然这可能有效,但它会在几乎硬件级别上等待按键事件,并且对平台独立性不友好。这是爱丽丝梦游仙境中一个潜在的兔子洞,因为它必须弄清楚各种各样的事件处理和代码必须知道它在哪个平台上运行。使用hasNext()布尔值false返回来指示输入流的结束应该在任何平台上工作,并且将避免在几乎硬件事件级别上处理键盘和按键的潜在不可移植的gee-whiz代码。

    以下程序执行您(和练习)想要的操作,如果用户在Windows平台上按ctrl-z或在Unix/Linux平台上按ctrl-d,而不必确定代码执行的平台,则将结束输入。

    // Exercise 6.16: EvenOrOddTest.java
    // Write a method isEven that uses the remainder operator (%)
    // to determine whether an integer is even. The method should
    // take an integer argument and return true if the integer is
    // even and false otherwise. Incorporate this method into an
    // application that inputs a sequence of integers (one at a time)
    // and determines whether each is even or odd.
    import java.util.Scanner;
    
    public class EvenOrOddTest {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
    
            int integer;
            System.out.println("Odd even integer test.");
            System.out.printf("Input CTRL-Z on Windows or CTRL-D on UNIX/Linux to end input\n"
                + "or an integer between values\n"
                + "%d and %d\n"
                + "to test whether it is odd or even: ",
                Integer.MIN_VALUE, Integer.MAX_VALUE);
            // the input.hasNext() will block until
            // some kind of input, even a CTRL-Z,
            // arrives in the stream
            // the body of the while loop will execute
            // every time input appears for as long as the input
            // is not a CTRL-Z
            while (input.hasNext()) { // repeat until end of input
                // prompt user
                // now see if the input we did get is an integer
                if (input.hasNextInt()) { // we got an integer...
                    integer = input.nextInt();
                    System.out.printf("\n%d is "
                            + (EvenOrOdd.isEven(integer) ? "even.\n\n" : "odd.\n\n"), integer);
                } else { // we got a non-integer one too large for int
                    System.out.printf("\nInput %s invalid! Try again...\n\n", input.next());                
                } // end if...else
                // white space (i.e. spaces and tabs) are separators
                // next and nextInt get only to the first separator
                // so it is possible for the user to enter an integer
                // followed by tabs and/or spaces followed by more
                // input, integer or not up to the end of the input line
                // input.nextLine() flushes everything not processed 
                // by the nextInt() or next() to the input line end 
                // won't block execution waiting for input
                // if there is nothing left on the input line
                input.nextLine();
                // prompt for user input again
                System.out.printf("Input CTRL-Z to end input\n"
                        + "or an integer between values\n"
                        + "%d and %d\n"
                        + "to test whether it is odd or even: ",
                        Integer.MIN_VALUE, Integer.MAX_VALUE);
            } // end while
        } // end main
    
        static boolean isEven(int integer) {
            // integer modulus 2 is zero when integer is even
            return ((integer % 2) == 0);
        } // end isEven
    } // end class EvenOrOddTest