【问题标题】:Reading and storing names in an array from user input从用户输入中读取名称并将其存储在数组中
【发布时间】: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


    【解决方案1】:

    你的问题在这里:

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

    【讨论】:

    • 我想弄清楚如何正确完成扫描输入
    • 已尝试按照您所说的那样指定数组,但我在“.. = new String[n];”中的 n 下得到一条弯曲的红线带有消息“类型不匹配:无法从字符串转换为 int”我是否必须将字符串解析为 int 或类似的东西?恐怕我的编程技能还有很多不足之处。
    • 是的,非常感谢队友 :) 所以我可以稍微回报一下;你是=你是。当谈论属于别人的任何东西时,你的词是正确的。
    • 哈哈你这语法纳粹!我匆匆回答了一下,但我知道区别别担心:P
    • 诚然,我是,但这只是因为它是我的母语:D
    猜你喜欢
    • 1970-01-01
    • 2012-01-05
    • 2017-06-25
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 2014-07-29
    • 2011-11-05
    • 1970-01-01
    相关资源
    最近更新 更多