无法弄清楚如何在java中将用户输入的名称添加到数组中

时间:2016-02-13 23:25:07

标签: java arrays

//询问用户他想要输入多少学生和成绩

\u0000

我希望能够在用户输入名称时添加名称,但是在格式正确之后。我只知道如何在用户输入字符串时立即将它们添加到字符串中

1 个答案:

答案 0 :(得分:1)

我认为您的问题是您需要在循环之外声明namesList

public void setup() {
    Scanner keyboard = new Scanner(System.in);

    System.out.print("Enter number of students: ");

    numStudents = keyboard.nextInt();
}

public void setName(String someName) {

    String[] nameList = new String[numStudents]; //out here

    for(int i = 0; i < numStudents; i++) {

        System.out.print("Enter name of student # " + (i+1) + ": ");

        Scanner keyboard = new Scanner(System.in);

        String nameRough = keyboard.nextLine();
        String name = nameRough.trim();

      // i have to ask the user to enter the name int he for Last, first and         then rearrange it so this is what thats doing

        String firstName = name.substring(name.indexOf(",")+1);
        String lastName = name.substring(0, name.indexOf(","));

        name = firstName + " " + lastName;

    //  name = nameList; 

        System.out.println("");

    // and then here is where i can't figure out how to add name to the           army at i 

        nameList[i] = name;

    }
}

否则,您正在创建循环的新列表每次迭代。您希望在每次迭代时创建一个新的名称,然后将其添加到此列表中,该列表在迭代期间保持不变。

您还遇到了一些语法问题,例如nameList vs namesList,并且在您第一次使用时未声明name