2015-06-26 22 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

我更新了答案,現在應該清楚=) –

相關問題