程序未终止

 收藏

我一直在做Java MOOC,但我坚持提交,因为尽管我得到了期望的输出,但是我的程序并未终止。

问题说:

Create a method called printText which prints the phrase "In a hole in the ground there lived a method" and a newline. Then expand the program so that the main program asks the user for the number of times the phrase will be printed (i.e. how many times the method will be called).

我认为问题可能出在我的while循环未终止。

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("How many times?");
    int n = Integer.valueOf(scanner.nextLine());
    int a = 0;
    while (true) {
        if (a < n) {
            printText();
            a++;
        }
    }
}

public static void printText() {
    System.out.println("In a hole in the ground there lived a method");
}
回复
  • You are almost on track, get rid of outer loop while loop and change if (a < n) to while(a<n)

    import java.util.*;
    public class Main
    {
        public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);
            System.out.println("How many times?");
            int n = Integer.valueOf(scanner.nextLine());
            int a = 0;
            while(a < n) {
                    printText();
                    a++;
    
    
            }
    
        }
        public static void printText() {
    
            System.out.println("In a hole in the ground there lived a method");
        }
    }
    

  • Your a < n condition should be associated with your loop. Although the if ensures that printText() is only called n times, it does not prevent the infinite loop from continuing forever:

    while (a < n) {
        printText();
        a++;
    }
    

    Alternatively, you can keep your infinite loop but break when a >= n:

    while (true) {
        if (a < n) {
            printText();
            a++;
        } else {
            break;
        }
    }
    

    但我认为第一种解决方案更具可读性。