簡體   English   中英

使用Java掃描器在接受用戶輸入時檢查兩個條件

[英]Using java scanner to check two conditions while taking user input

我需要用戶輸入一個介於1和301之間的整數。我這里有一個簡單的循環來檢查用戶輸入。 我只是想從用戶的單一號碼,如果用戶輸入比1和301之間的一個int以外的任何其他,我想要顯示的打印線,並提示用戶,直到他們進入一個有效的輸入再試一次。

        while (!sc.hasNextInt()) {
            System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
            sc.next();
        }
        int numToCheck = sc.nextInt();
        // do stuff with numToCheck

這將檢查輸入是否為int,但是我似乎找不到找到給int輸入一個界限的方法。 我嘗試將用戶輸入分配給變量,然后檢查條件輸入<1或輸入> 301,但是如果用戶輸入字母,則會收到InputMismatchException。 我應該如何存儲用戶輸入? (我想將其存儲為一個int來檢查條件,但由於不知道用戶將輸入什么,所以不能這樣做)。

也許有一個更好的設計可以完成所有這一切。 這些也受到歡迎。

提前致謝。

您沒有保存輸入的的值。 因此,您的程序每次看到"sc.nextInt()"時都在等待用戶輸入數字,將輸入分配給變量,然后檢查條件。 編輯:好的,我會為您付出更多的努力。 看看是否可行。

***說明了用戶可能輸入字符而不是數字的情況。

import java.util.*;
public class HelloWorld{

public static void main(String []args){
    Scanner sc = new Scanner(System.in);
    int input;
    while (true){
        if (sc.hasNextInt()){
             input = sc.nextInt(); // Assign the next integer to a variable
             if (input  <= 301  && input >= 1){ // Check if integer meets condition
                   break; // Condition met, break out of loop
            }
        }else{
              sc.next();
        }
        System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
    }
}

}

假設您只需要用戶輸入1次,請嘗試遵循以下簡單代碼,該代碼將接受用戶輸入,直到用戶輸入有效輸入為止。

Scanner in = new Scanner(System.in);
     int flag = 0,x=0;
     while(flag == 0){
         x = in.nextInt();
         if(x<1 || x>301){
             flag = 0;
             System.out.println("Invalid Input.");
         }
         else{
             flag = 1;
         }
     }

並且,如果您希望用戶輸入多個輸入(即此處為3個),則應設置一個隨用戶的每個有效輸入而增加的計數器,如下所示:

 Scanner in = new Scanner(System.in);
     int flag = 0,x=0,count = 1;
     while(flag == 0){
         x = in.nextInt();
         if(x<1 || x>301){
             flag = 0;
             System.out.println("Invalid Input.");
         }
         else{
             //executes when input is valid
             if(count == 3){
                 flag = 1;
             }
             count++;

         }
     }

編輯:

如果還想檢查輸入是否為Integer ,則必須在上面的代碼中添加一個附加條件。 正如您所說的,您只需要用戶輸入一次而不是3輸入,您必須更改退出條件。 更改代碼如下:

Scanner in = new Scanner(System.in);
 int flag = 0,count = 1,x=0,flag1 = 0;
 String y;
 while(flag == 0){
     y = in.next();
     flag1 = 0;
     try{
         x = Integer.parseInt(y);
     }
     catch(NumberFormatException e){
         flag1 = 1;
         System.out.println("Invalid Input.");
     }
     if((x<1 || x>301)&&flag1 == 0){
         flag = 0;
         System.out.println("Invalid Input.");
     }
     else if(flag1 == 0){
         //executes when input is valid
         if(count == 1){   // put count == 3 if you want 3 inputs from user.
             flag = 1;
         }
         count++;
     }
 }

在這里,我們將輸入作為String而不是通過使用Integer.parseInt()String轉換為Integer 如果String不是Integer ,則它將引發異常,我們將繼續循環直到用戶輸入有效輸入為止。

我運行了這段代碼,以查看它是否會顯示出比您更好的性能。

Scanner sc = new Scanner(System.in);

boolean valid = true;
do {
    if (!valid) {
        System.out.print("Invalid Input. ");
    }
    System.out.print("Please enter a valid number between 1 and 301: ");
    String input = sc.next();
    try {
        int value = Integer.parseInt(input);
        valid = (value >= 1 && value <= 301);
    } catch (NumberFormatException nfex) {
        valid = false;
    }
} while (!valid);

當轉換為整數失敗時,JVM會掛起一點。 我相信您的問題更多與Scanner在幕后執行的“嘗試/捕獲”機制有關,而不是與設計有關。

使用WHILE作為結果

  do{
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
  }while( x < 20 );

好 ?

暫無
暫無

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

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