Java二维数组学生记录输入
我正在学习Java,我已经做了两天这个练习了。我在互联网上搜寻答案,但似乎找不到解决我问题的最佳答案: 1.如何将输入的字符串(如fName、mName//或我做得对吗?)存储到二维数组中。我见过一些语法如下的示例程序:Java二维数组学生记录输入,java,bufferedreader,Java,Bufferedreader,我正在学习Java,我已经做了两天这个练习了。我在互联网上搜寻答案,但似乎找不到解决我问题的最佳答案: 1.如何将输入的字符串(如fName、mName//或我做得对吗?)存储到二维数组中。我见过一些语法如下的示例程序: fName = fName.getText(); lName = lname.getText(); 但它们似乎不符合我试图编写的代码,我也无法绕过它,因为我只是一个乞丐 如何打印所有输入后的所有循环的事情。与用户在“输入学生人数”中输入“4”时一样,将打印4个学生信息 以下是
fName = fName.getText();
lName = lname.getText();
但它们似乎不符合我试图编写的代码,我也无法绕过它,因为我只是一个乞丐
import java.io.*;
public class Main {
public static void main(String[] args)throws IOException{
BufferedReader datain = new BufferedReader (new InputStreamReader (System.in));
String fName, lName, course, yrLevel, bDate;
int age;
int arr [] [];
int size;
System.out.print("Enter number of students: \n");
size = Integer.parseInt(datain.readLine());
arr = new int [size][];
for(int a = 0; a < arr.length; a++){
System.out.print("Enter first name: \n");
fName = datain.readLine();
/*insert code here to store fName to two dimensional array
like this one? arr [0] = new int [a]; */
System.out.print("Enter last name: ");
lName = datain.readLine();
System.out.print("Enter course: ");
course = datain.readLine();
System.out.print("Enter year level: ");
yrLevel = datain.readLine();
System.out.print("Enter age: ");
age = Integer.parseInt(datain.readLine());
}
/* desired output be like:
Student 1
Name: Bat Man
Year Level: Graduate School
Birthdate: Feb. 20, 2012
Age: 7
Student 2
Name: Super Man
Year Level: Masteral
Birthdate: Jan. 1, 2012
Age: 8
*/
System.out.println("Name: " +arr[0][0] + " " + arr[0] [1]); //just me showing my non-working idea of printing them.
}
}
import java.io.*;
公共班机{
公共静态void main(字符串[]args)引发IOException{
BufferedReader datain=新的BufferedReader(新的InputStreamReader(System.in));
字符串fName、lName、course、yrLevel、bDate;
智力年龄;
int arr[][];
整数大小;
System.out.print(“输入学生人数:\n”);
size=Integer.parseInt(datain.readLine());
arr=新整数[size][];
对于(int a=0;a
您应该创建一个小对象来存储学生详细信息,而不是使用多维数组。像这样:
public class Student {
public String name;
public String yearLevel;
//etc...
//constructor
public Student(String name, String yearLevel, etc...) {
this.name = name;
this.yearLevel = yearLevel;
//etc...
}
}
然后从用户输入中获取数据,并使用它构造一个学生。然后学生可以存储在一个数组中:
Student[] students = new Student[numberOfStudents];
或者更好的是,您可以将学生存储在数组列表中,这样您就不必知道所需的学生人数:
ArrayList<Student> students = new ArrayList<Student>();
ArrayList students=new ArrayList();
我不确定您为什么要使用2d阵列来进行此操作?为什么不制作一个存储学生详细信息的小对象,然后创建一个1d数组,甚至创建一个学生对象的数组列表呢?我不知道这将如何编译。根据@DavidSaxon所说的,我不确定使用2D数组是否可以实现您想要的功能。您需要多个阵列(6个1D阵列)。或者一个由Student
对象组成的一维数组。基于这个问题,听起来物体是不可能的。如果你真的想使用多维数组,你可以在第一维存储每条记录的索引,在前6维存储每个值。问题的要点实际上是关于二维数组。例如:如果输入为4,则将创建一个数组:A[0][0]A[0][1]A[0][2]A[0][3]A[0][4]A[1][0]A[1][1]A[1][2]A[1][3]A[1][4]A[2][1]等,直到完成第一个循环后,学生的[4][4]A[1:fName将存储在[0][0]中,lName将存储在[0][1]中,它请求学生2,然后fName将存储在[1][0]中lName将存储在[1][1]中。。