Java 从用户输入读取名称并将其存储在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31069384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:36:20  来源:igfitidea点击:

Reading and storing names in an array from user input

javaarraysstringfor-loopjava.util.scanner

提问by Brody

I'm currently in the midst of creating a program that takes in 10 names from user input, stores them in an array and then prints them out in upper case. I know there's been similar threads/questions asked but none of them really helped me. As per, any help would be greatly appreciated.

我目前正在创建一个程序,该程序从用户输入中获取 10 个名称,将它们存储在一个数组中,然后将它们以大写形式打印出来。我知道有人问过类似的主题/问题,但没有一个真正对我有帮助。按照,任何帮助将不胜感激。

My code:

我的代码:

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

}

}

The current error I'm getting is this (after only 3 inputs I may add):

我得到的当前错误是这样的(仅在我可以添加 3 个输入之后):

Enter 10 names: 
Tom
Steve
Phil
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ReadAndStoreNames.main(ReadAndStoreNames.java:22)

采纳答案by Roel Strolenberg

Your problem is here:

你的问题在这里:

String [] names = {n};

The size of namesis now 1, with the value 10. What you want is:

的大小names现在是 1,值为 10。你想要的是:

String [] names = new String[n];

The latter is the correct syntax for specifying sizeof arrays.

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

EDIT:

编辑:

It seems like you want to read nusing the scanner. nextLinecan be anything, so not just an integer. I would change the code to this:

您似乎想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();

}

}