Create a class Student with attributes name(String) and registrationNo(int) and a method show to display the attributes of the Student. Write a menu driven program with 2 choices to take the input of the student attributes and display the attributes.
Input Format
Your program should take the 2 choice as input. • If the first input will be 1 then also ask to user to enter the details of the student. If the entered registrationNo is negative, do not accept the input and prompt again to take new input until user will not entered the positive registrationNo. • If the first input will be 2 then display the default values of Student attributes separated by comma in the same line. • If the first input will be any other int value, display the message “Wrong Choice”.
Constraints
Student registrationNo should be positive value(excluding 0).
Output Format
Your program should display the attributes of Student or the message “Wrong Choice” as the User choice at the runtime.
Sample Input 0
1
John
10
Sample Output 0
John,10
Sample Input 1
2
Sample Output 1
null,0
Solution
import java.util.Scanner;
class Student {
private String name;
private int registrationNo;
// Constructor to initialize the default values of attributes
public Student() {
this.name = null;
this.registrationNo = 0;
}
// Method to display the attributes of the student
public void show() {
System.out.println(this.name + "," + this.registrationNo);
}
// Method to set the name of the student
public void setName(String name) {
this.name = name;
}
// Method to set the registration number of the student
public void setRegistrationNo(int registrationNo) {
this.registrationNo = registrationNo;
}
}
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Create an instance of the Student class
Student student = new Student();
// Take the input choice from the user
int choice = sc.nextInt();
if (choice == 1) {
// Take input details from the user
String name = sc.next();
student.setName(name);
int registrationNo = 0;
boolean validInput = false;
while (!validInput) {
try {
registrationNo = sc.nextInt();
if (registrationNo > 0) {
validInput = true;
} else {
}
} catch (Exception e) {
sc.nextLine(); // consume the input buffer to prevent an infinite loop
}
}
student.setRegistrationNo(registrationNo);
// sauravhathi
// Display the attributes of the student
student.show();
} else if (choice == 2) {
// Display the default values of the student
student.show();
} else {
System.out.println("Wrong Choice");
}
sc.close();
}
}
Happy Learning – If you require any further information, feel free to contact me.