The question requires us to create two objects of the Student class and have 5 variables. The variables will be assigned a value each through user input.
Is there a way to use a loop or anything else to take the user inputs from there instead of writing each variable individually using the dot operator?
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student student1 = new Student();
Student student2 = new Student();
//Input for student 1
student1.name = input.nextLine();
student1.gender = input.next().charAt(0);
student1.cgpa = input.nextDouble();
student1.roll[0] = input.nextInt();
student1.age = input.nextInt();
//Input for student 2
student2.name = input.nextLine();
student2.gender = input.next().charAt(0);
student2.cgpa = input.nextDouble();
student2.roll[0] = input.nextInt();
student2.age = input.nextInt();
}
}
class Student {
String name;
char gender;
double cgpa;
int[] roll;
int age;
}
CodePudding user response:
We can create a constructor for the class Student
that takes in the parameters and defines them as so:
class Student {
String name;
char gender;
double cgpa;
int[] roll = new int[10];
int age;
public Student(String n,char g,double c,int r,int a){
name = n;
gender = g;
cgpa = c;
roll[0] = r;
age = a;
}
public String toString(){
return name;
}
}
Note that we must give roll
a specified length before assigning it any elements. Alternatively, we could use an ArrayList
instead of an array for roll
if we are not given the length (I used 10 as a placeholder).
As for the main method, we can now define student1
and student2
in one line each:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student student1 = new Student(input.nextLine(), input.next().charAt(0), input.nextDouble(), input.nextInt(), input.nextInt());
input.nextLine();
Student student2 = new Student(input.nextLine(), input.next().charAt(0), input.nextDouble(), input.nextInt(), input.nextInt());
System.out.println(student1);
System.out.println(student2);
}
}
Notice how between the declarations of student1
and student2
there is a input.nextLine()
. This is because after we take the final parameter, an integer, for student1
, the input will leave a trailing newline which will mess with the user input for student2
. To fix this, we can scan the line to get rid of the whitespace.
I hope this helped! Please let me know if you need any further clarification or details :)
CodePudding user response:
List.of(student1, student2, student3, student4).forEach(student ->{
student.name = input.nextLine();
student.gender = input.next().charAt(0);
student.cgpa = input.nextDouble();
student.roll[0] = input.nextInt();
student.age = input.nextInt();
});