我目前正在创建一个程序,该程序从用户输入中获取 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)
最佳答案
你的问题在这里:
String [] names = {n};
names
的大小现在为 1,值为 10。
你想要的是:
String [] names = new String[n];
后者是指定数组大小
的正确语法。
编辑:
您似乎想使用扫描仪阅读n
。 nextLine
可以是任何东西,所以不仅仅是一个整数。我会将代码更改为:
import java.util.Scanner;
public class ReadAndStoreNames {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("How many names would you like to enter?")
int n = scan.nextInt(); //Ensures you take an integer
System.out.println("Enter the " + n + " names: ");
String [] names = new String[n];
//store the names in an array
for (int i = 0; i < names.length; i++){
names[i] = scan.nextLine();
}
//sequentially print the names and upperCase them
for (String i : names){
System.out.println(i.toUpperCase());
}
scan.close();
}
}
关于java - 从用户输入中读取名称并将其存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31069384/