2015-06-26 26 views
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) 

回答

3

你的问题是在这里:

String [] names = {n}; 

names的尺寸现在为1,值为10. 你想要的是:

String [] names = new String[n]; 

后者是指定size数组的正确语法。

编辑:

好像要使用扫描仪读取nnextLine可以是任何东西,所以不只是一个整数。我会改变的代码如下:

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(); 

} 

} 
+0

我试图找出如何正确地完成扫描输入 –

+0

试图指定数组就像你说的,但我得到第n下一个波浪红线” .. =新的字符串[n];“与消息“类型不匹配:不能从字符串转换为int” 我需要将字符串解析为int或类似的东西吗?我的编程技巧让我很害怕。 – Brody

+0

我更新了答案,现在应该清楚=) –

相关问题