在用户输入整数之前,如何使程序保持循环

时间:2015-01-31 17:32:38

标签: java do-while

我正在尝试修改我的程序,以便即使用户输入了字符串而不是程序崩溃,它也应该保持循环并要求用户输入需要为整数的考试成绩,仅限用户如果程序终止,则输入一个整数。我指的是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();

}

  }

4 个答案:

答案 0 :(得分:0)

使用布尔变量来跟踪是否保持循环。例如:

boolean loop = true;
do {
    // set loop to false when you want to end
} while(loop);

答案 1 :(得分:0)

所以你可以这样做:

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

答案 2 :(得分:0)

而不是假设输入的数字是int,您可以将其输入为String并循环,直到该字符串代表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
    }
}

答案 3 :(得分:0)

您是否考虑过使用JOptionPane来获取用户的输入?它能够显示一个带有文本字段的小窗口以及一个完全符合您需求的“确定”和“取消”按钮。

以下是JOptionPane#showInputDialog:

的文档
static String showInputDialog(Component parentComponent, Object message, String title, int messageType) 
  

显示一个对话框,请求来自父组件父级的用户输入,对话框具有标题标题和消息类型messageType。