簡體   English   中英

使用掃描儀時驗證用戶輸入

[英]Validation of user input while using Scanner

我在使用Scanner獲取用戶輸入並將其存儲在變量中時遇到麻煩。 問題是,當用戶輸入輸入時,方法將進入無限循環。

即,用戶可以輸入任何值或空格,但程序不會將其用作輸入,而是繼續進行將它們分配給變量的下一步。

public class AS10 {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        double X = 0;
        double Y = 0;
        System.out.println("please enter the value of X-cordinate and Y cordinate :");
        Scanner scn = new Scanner(System.in);
        while (scn.hasNext()){
         X = scn.nextDouble();
         Y = scn.nextDouble();
        }

        System.out.println("  the value of y is " + Y+ "the value of x is "+ X);
    }
}

您不需要while循環。 您的代碼中沒有任何東西會導致循環結束。

只要刪除它,您的代碼就可以工作。

public static void main(String[] args) {
    double X = 0;
    double Y = 0;
    System.out.println("please enter the value of X-cordinate and Y cordinate :");
    Scanner scn = new Scanner(System.in);
    X = scn.nextDouble();
    Y = scn.nextDouble();

    System.out.println("  the value of y is " + Y + " the value of x is " + X);
}

Scanner類的hasNext方法檢查輸入中是否有可用令牌。 您不需要while循環來進行錯誤處理。 將賦值語句(從nextDouble方法獲取值)放在try catch塊中,並相應地處理異常。

或者,您可以使用hasNextDouble方法來檢查輸入中是否有可用的double值。

該程序將產生所需的輸出(只需將print語句包括在while循環中):

public static void main(String... args) {

    double X = 0;
    double Y = 0;
    System.out.println("please enter the value of X-cordinate and Y cordinate :");
    Scanner scn = new Scanner(System.in);
    while (scn.hasNext()) {
        X = scn.nextDouble();
        Y = scn.nextDouble();
        System.out.println("  the value of y is " + Y + "the value of x is " + X);
    }

}

while循環不會終止(直到按Ctrl + C或終止Java進程)。

暫無
暫無

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

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