本文介紹了如何循環用戶輸入,直到輸入整數?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想運行一個交互式程序,提示用戶輸入一些學生。如果用戶除輸入整數外還輸入字母或其他字符,則應再次詢問(“輸入學生人數:”)
我有以下代碼:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
如何為此創建循環?
推薦答案
試試
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
這篇關于如何循環用戶輸入,直到輸入整數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,