簡體   English   中英

我如何使程序保持循環,直到用戶輸入了整數

[英]How do i make the program keep looping until the user has entered an integer

我正在嘗試修改程序,以便即使用戶輸入了字符串而不是程序崩潰,它也應繼續循環並要求用戶輸入必須為整數的考試成績,僅當用戶輸入了整數,程序應終止。 我指的是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();

}

  }

使用布爾變量來跟蹤是否繼續循環。 例如:

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

相反的假設inputed數為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
    }
}

您是否考慮過使用JOptionPane從用戶那里獲取輸入? 它能夠顯示一個帶有文本字段以及“確定”和“取消”按鈕的小窗口,非常適合您的需求。

這是JOptionPane#showInputDialog的文檔:

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

顯示一個對話框,該對話框請求以parentComponent為父級的用戶輸入,該對話框具有標題標題和消息類型messageType。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM