I'm studying Java and I've been working on this exercise for 2 days now. I've foraged the internet for answers but I can't seem to find the best one to solve my problem which are: 1. How to store the Strings input (like fName, mName //or am i doing this right?) into a two dimensional array. I've seen some sample programs with the syntax like:
fName = fName.getText();
lName = lname.getText();
but they don't seem to fit with what i'm trying to code and i can't go around it either coz im just a begginer.
Here is my initial non-working code:
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.
}
}
Rather than using a multi-dimensional array you should create a small object that stores student details. Like this:
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...
}
}
Then get the data from the user input and construct a student using it. And the students can then be stored in an array:
Student[] students = new Student[numberOfStudents];
Or even better you can store the students in an array list, then you don't have to know the number of students required:
ArrayList<Student> students = new ArrayList<Student>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.