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
我更新了答案,现在应该清楚=) –