Java 如何使程序保持循环,直到用户输入整数

Java 如何使程序保持循环,直到用户输入整数,java,do-while,Java,Do While,我试图修改我的程序,这样即使用户输入了字符串而不是程序崩溃,它也应该继续循环并要求用户输入需要为整数的考试分数,只有当用户输入了整数时,程序才会终止。我指的是do while块中的代码 import java.util.InputMismatchException; import java.util.Scanner; public class CatchingException { public static void main(String[] args) { Scanner s

我试图修改我的程序,这样即使用户输入了字符串而不是程序崩溃,它也应该继续循环并要求用户输入需要为整数的考试分数,只有当用户输入了整数时,程序才会终止。我指的是do while块中的代码

import java.util.InputMismatchException;
import java.util.Scanner;


public class CatchingException {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int score;
    String choice;


    try {
    System.out.println("Enter your percentage mark: ");
    score = scan.nextInt();


    do {
        if(score <40) {
            System.out.println("You FAILED");
        }else if(score >=40 && score <50){
            System.out.println("Your grade: PASS MARK");
        }else if(score >=50 && score <60) {
            System.out.println("Your grade: 2:2");
        }else if (score >=60 && score <70) {
            System.out.println("Your grade: 2:1");
        }else {
            System.out.println("Your grade: 1:1");
        }

        System.out.println("Do you want to enter another grade: ");
        choice = scan.next();
        if(choice.equalsIgnoreCase("yes")) {
            System.out.println("Enter your percentage mark: ");
                score = scan.nextInt();
                System.err.println("Incorrect Input");
            }
    }while();

    }catch(InputMismatchException e) {
        System.err.println("Incorrect Input ");
    }

    System.out.println("program terminated");
    scan.close();

}

  }
import java.util.InputMismatchException;
导入java.util.Scanner;
公共类捕获异常{
公共静态void main(字符串[]args){
扫描仪扫描=新扫描仪(System.in);
智力得分;
字符串选择;
试一试{
System.out.println(“输入您的百分比标记:”);
score=scan.nextInt();
做{

如果(score=40&&score=50&&score=60&&score使用布尔变量跟踪是否保持循环。例如:

boolean loop = true;
do {
    // set loop to false when you want to end
} while(loop);
所以你可以做:

int score = null;
boolean isInt = false;

do {
    System.out.println("Enter your percentage mark:");

    try {
        score = scan.nextInt();
        isInt = true;
    } catch (InputMismatchException e) {
        //Not An Integer
        isInt = false;
    }
} while(false)

//Do you if statements here if it gets out of the while loop which means the user entered an int

不必假设输入的数字是
int
,您可以将其作为
字符串输入并循环,直到该字符串表示
int

int intScore;
String score;
boolean gotInt = false;
while (!gotInt) {
    score = scan.next();
    try {
        intScore = Integer.valueOf(score);
        gotInt = true;
    } catch (NumberFormatException e) {
        // output some warning
    }
}

您是否考虑使用JopTePANE从用户那里获得一个输入?它能够显示一个带有文本字段和一个OK和取消按钮的小窗口,它可以很好地满足您的需求。 以下是JOptionPane#showInputDialog的文档:

static String showInputDialog(Component parentComponent, Object message, String title, int messageType) 
显示一个对话框,请求作为parentComponent父对象的用户输入,该对话框的标题和消息类型为messageType