'Assign multiple values of objects using a loop
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
