以下是我將如何重構您的代碼。我會在下面解釋的變化:
private static final String STATEMENT = "This input is of type ";
public static String checkInput(Scanner scanner) {
if (scanner.hasNextFloat()) {
return STATEMENT + Float.class.getSimpleName();
else if (scanner.hasNextInt()) {
return STATEMENT + Integer.class.getSimpleName();
}
return STATEMENT + "UNKNOWN";
}
- 首先,我們拉出來
statement
成constant,因爲它沒有被改變。
- 其次,我們通過
Scanner
作爲參數,而不是構建一個新的。有多種原因可以選擇,但原則是您應避免在System.in
中創建多個Scanner
實例 - 通常您會在main()
方法中創建這樣的Scanner
,並將其傳遞給需要的方法和類使用它。
- 接下來,我們使用
has*()
方法檢查掃描儀的狀態,而不是直接從掃描儀讀取數據,而不是直接從掃描儀讀取數據。這改變了checkInput()
的語義,因爲當它返回被檢查的輸入時仍然在掃描器中,但這與名爲check...()
的方法更爲一致 - 應該檢查,而不是更改狀態。因爲你的實現調用.next()
你失去了實際提供的輸入,這可能是不可取的。
- 最後,我們
return
從每個塊內,而不是設置一個臨時inputType
變量,並在最後返回它。
你main()
方法現在看起來可能是這樣:
public static void main(String[] args) {
// using try-with-resources so we don't have to call .close()
try (Scanner scanner = new Scanner(System.in)) {
System.out.println(checkInput(scanner));
String input = scanner.next(); // this actually advances the scanner
System.out.println("You input: " + input);
}
}
採取進一步行動,你可能更喜歡讓checkInput()
返回Class<?>
而非String
,然後分別構建你的聲明。這將允許您以不同方式處理輸入。例如:
public static Class<?> inputType(Scanner scanner) {
if (scanner.hasNextFloat()) {
return Float.class;
else if (scanner.hasNextInt()) {
return Integer.class;
}
// add other types as needed
return String.class;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
Class<?> inputType = inputType(scanner);
String input = scanner.next();
System.out.println("You input: " + input);
if (inputType.equals(Integer.class)) {
System.out.prinln("That's a valid integer!");
}
}
}
所有這一切說,我們非常這裏重新發明輪子。 「正確」的方式來使用Scanner
是直接使用的類型的方法 - 例如: -
if (scanner.hasNextInt()) {
int value = scanner.nextInt();
}
這避免了需要做任何手動型檢查或類似的無用功 - 只是讓Scanner
爲你做驗證。
將第三行改爲'String inputType =「UNKNOWN」;' - 如果你的'try'塊都失敗了,你會返回''這個輸入的類型是UNKNOWN'''。 – dimo414
@ dimo414但考慮到第五行,如果輸入不是float或Integer,它總是會返回inputType作爲字符串。 –
@Vic你能提供任何幫助或鏈接,我怎麼能使用它。 –