无效输入后重复循环

时间:2018-10-14 22:25:36

标签: loops while-loop

所有计算都可以。当我得到一个无效的条目并且用户输入一个新的正整数时,我遇到了一个问题。它不会再次开始循环。任何建议,我们将不胜感激!

    public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int start;
    int i;
    double squareRoot;

    System.out.println("Please enter a positive integer: ");
    start = in.nextInt();

        if (start > 0){
        do {

            squareRoot = Math.sqrt(start);
            start--;
            System.out.printf("%.4f", squareRoot);
            System.out.println();
        }
        while (start >= 0);
        }

    else {
            System.out.println("The number you entered is not a postive integer.");
            System.out.println("Please enter an integer greater than zero: ");
            start = in.nextInt();
            }
}

}

1 个答案:

答案 0 :(得分:0)

如果需要一遍又一遍地重复相同的步骤,则需要循环。因此,添加一个带有简单条件的while循环,让它一遍又一遍。

这是示例代码。我不得不给出退出选项,所以以-1作为提示。

import java.util.Scanner;
public class HelloWorld {
 public static void main(String[] args) {

Scanner in = new Scanner(System.in);
int start;
int i;
double squareRoot;


System.out.println("Please enter a positive integer: ");
boolean quit = false;
while (!quit) {
    System.out.println("Enter the integer");    
start = in.nextInt();    
    if (start > 0){
    do {

        squareRoot = Math.sqrt(start);
        start--;
        System.out.printf("%.4f", squareRoot);
        System.out.println();

    }
    while (start >= 0);
    }
else if (start == -1) {
   quit = true;
}
else {
        System.out.println("The number you entered is not a postive integer.");
        System.out.println("Please enter an integer greater than zero: ");
}
}
}

}