【发布时间】:2015-06-26 09:17:33
【问题描述】:
我目前正在创建一个程序,该程序从用户输入中获取 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)
【问题讨论】:
标签: java arrays string for-loop java.util.scanner