1
我目前正在創建一個程序,該程序從用戶輸入中獲取10個姓名,將它們存儲在數組中,然後以大寫形式打印出來。我知道有類似的線索/問題,但他們都沒有幫助我。根據任何幫助將不勝感激。從用戶輸入中讀取並存儲數組中的姓名
我的代碼:
import java.util.Scanner;
public class ReadAndStoreNames {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
//take 10 string values from user
System.out.println("Enter 10 names: ");
String n = scan.nextLine();
String [] names = {n};
//store the names in an array
for (int i = 0; i < 10; i++){
names[i] = scan.nextLine();
}
//sequentially print the names and upperCase them
for (String i : names){
System.out.println(i.toUpperCase());
}
scan.close();
}
}
的當前錯誤,我得到的是這種(只有3輸入後,我可以補充):
Enter 10 names:
Tom
Steve
Phil
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ReadAndStoreNames.main(ReadAndStoreNames.java:22)
我試圖找出如何正確地完成掃描輸入 –
試圖指定數組就像你說的,但我得到第n下一個波浪紅線」 .. =新的字符串[n];「與消息「類型不匹配:不能從字符串轉換爲int」 我需要將字符串解析爲int或類似的東西嗎?我的編程技巧讓我很害怕。 – Brody
我更新了答案,現在應該清楚=) –