我正在学习Java,现在我已经在这个练习中工作了2天。我已经在互联网上搜索答案,但我似乎无法找到解决我问题的最佳方法: 1.如何将字符串输入(如fName,mName //或我这样做?)存储到二维数组中。我见过一些示例程序的语法如下:
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.
}
}
答案 0 :(得分:0)
您应该创建一个存储学生详细信息的小对象,而不是使用多维数组。像这样:
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>();