猿问

将多个用户输入存储到多个单独的数组中

我对编程非常陌生。我正在尝试编写一个程序,允许用户逐个课程进入他们的学院/大学成绩单课程。我希望每个课程都以自己的数组分隔,并用空格分隔。


例如: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();


}


}


德玛西亚99
浏览 127回答 2
2回答

守着星空守着你

有 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++){&nbsp; &nbsp; System.out.println("Course "+(counter+1));&nbsp; &nbsp; //Solution&nbsp; &nbsp; courses[counter] = input.next().split("-");&nbsp; //data are separated by "-"&nbsp; &nbsp; input.nextLine(); //Cleanning buffer}

开心每一天1111

要实现您想要的内容,可以像这样工作: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++){&nbsp; &nbsp; System.out.println("Course "+(counter+1));&nbsp; &nbsp; courses[counter] = input.nextLine().split("\\s+");&nbsp; &nbsp;}由于这是拆分课程,因此它会生成一个数组数组,如下所示:[["ENG","105","A","3"], ["MAT", "102", "A", "4"]]&nbsp;另一方面,如果要在用户输入关键字时停止输入,则需要如下所示的内容: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")){&nbsp; &nbsp; courses.add(course.split("\\s+"));&nbsp;&nbsp;&nbsp; &nbsp; String course = input.nextLine();&nbsp;}
随时随地看视频慕课网APP

相关分类

Java
我要回答