2016-01-20 29 views
1

我是編程新手,目前我正在關注一個Java類,我必須驗證用戶的掃描器輸入。下面的代碼似乎工作,但我認爲它有點低效。必須有更好的方法來做到這一點!驗證掃描儀的輸入:是一個整數,並在一定的數字範圍內?

歡迎您的建議!

下面是我得到了什麼:

do { 
    System.out.println("What is you age?"); 
    while (!scSudoku.hasNextInt()) { 
     System.out.println("You must enter an number"); 
     scSudoku.next(); 
    } 
    age = scSudoku.nextInt(); 
    if (age < 10 || age > 90) { 
     System.out.println("You age must be within 10 and 90"); 
    } 
} while (age < 10 || age > 90); 

回答

1

使用nextLine()放棄任何不良輸入。

通過使用永無止境的循環防止代碼複製,並且使用breakreturn來退出循環。我更喜歡用輔助方法隔離代碼並使用return

private static int promptAge(Scanner sc) { 
    System.out.println("What is you age?"); 
    for (;;) { 
     if (! sc.hasNextInt()) { 
      System.out.println("You must enter an number"); 
     } else { 
      int age = sc.nextInt(); 
      if (age >= 10 && age <= 90) 
       return age; 
      System.out.println("You age must be within 10 and 90"); 
     } 
     sc.nextLine(); // discard (rest of) line of input 
    } 
} 
0

嘗試用scSudoku.nextLine更換scSudoku.next();。它可能會運行得更順暢,但我的Java有點生疏。 我記得使用nextLinenextln而不是隻是next,和程序工作。

編輯: 嘗試用scSudoku.nextln代替scSudoku.next();。看來,nextln更廣泛的使用。編輯2: 或只使用nextWhateverYou'reUsing

+0

Java的['Scanner'(https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html)不具有'nextln()'方法。 – Andreas

+0

@Andreas它似乎爲我工作。 –

+0

如果是這樣的話,你可以提供鏈接到定義'nextln()'方法的javadoc嗎?也許可以參考「更廣泛使用」的說法或舉例? – Andreas

相關問題