将多个用户输入存储到多个单独的阵列中

时间:2019-04-10 18:34:04

标签: java arrays input

我是编程的新手。我正在尝试编写一个程序,允许用户按课程输入他们的大学/大学成绩单。我希望每个课程都以各自的数组分隔并以空格分隔。

例如:ENG 105 A 3(阵列1)MAT 102 A 4(阵列2)等...

似乎输入被存储在一个数组中。

如果我不必使用计数器,并且程序可以在用户完成课程输入后继续运行,那就太好了。

import java.util.Scanner;

public class Tester{

public static void main(String[] args) {

 int length;
 Scanner input = new Scanner(System.in);

 System.out.println("How many courses did you complete at your college / university?: ");
 length = input.nextInt();  

 String[] courses = new String[length];

 System.out.println("Follow this model when entering your courses: ENG 105 3 A");

 for(int counter = 0; counter < length; counter++){
  System.out.println("Course "+(counter+1));
  courses[counter] = input.next();   
 }

 input.close();

}

}

2 个答案:

答案 0 :(得分:1)

有2点要解决:处理数据(ENG-105-3-A)和缓冲区。

String[][] courses = new String[length][4];

System.out.println("Follow this model when entering your courses: ENG-105-3-A");

for(int counter = 0; counter < length; counter++){
    System.out.println("Course "+(counter+1));

    //Solution
    courses[counter] = input.next().split("-");  //data are separated by "-"

    input.nextLine(); //Cleanning buffer

}

答案 1 :(得分:0)

要实现所需的功能,就可以这样做:

String[][] courses = new String[length][];

System.out.println("Follow this model when entering your courses: ENG 105 3 A");

for (int counter = 0; counter < length; counter++){
    System.out.println("Course "+(counter+1));
    courses[counter] = input.nextLine().split("\\s+");   
}

由于这将拆分课程,因此会生成一个数组数组,如下所示:

[["ENG","105","A","3"], ["MAT", "102", "A", "4"]] 

另一方面,如果要在用户输入关键字时停止输入,则需要这样的内容:

List<String[]> courses = new ArrayList<String[]>;

System.out.println("Follow this model when entering your courses: ENG 105 3 A");
String course = input.next();
while (!course.equals("end")){
    courses.add(course.split("\\s+"));  
    String course = input.nextLine(); 
}