In: Computer Science
Code in Java
Write a Student class which has two instance variables, ID and name. This class should have a two-parameter constructor that will set the value of ID and name variables. Write setters and getters for both instance variables. The setter for ID should check if the length of ID lies between 6 to 8 and setter for name should check that the length of name should lie between 0 to 20. If the value could not be set, print a relevant message stating value could not be changed.
Finally, code a main method that will create an instance of Student class with ID as “5678654” and name as “Shawn” then print the ID and name to screen. Then use the setters to set the value of ID to “123456789” and name to “JohnCarlo” and then print the values of ID and name by using their getters.
Here is the complete java code:
public class Student {
// Making id as int and name as string
private int ID;
private String name;
// Here is the constructor with id and name as parameters
Student(int id, String n) {
ID = id;
name = n;
}
// gettter for id
int getId() {
return ID;
}
// getter for name
String getName() {
return name;
}
// setter for id
void setID(int newId) {
// Here we convert int to string so we can calculate the length and verify that
// it is between 6 and 8
if (String.valueOf(newId).length() < 6 || String.valueOf(newId).length() > 8) {
// if it is not then we print the message and return from the function
System.out.println("The length should be between 6-8 for ID");
return;
}
ID = newId;
}
// setter for name
void setName(String newname) {
// if length is not between 0 and 20 then we show message and return
if (newname.length() <= 0 || newname.length() > 20) {
System.out.println("The length should be between 0-20 for name");
return;
}
name = newname;
}
// This is the main function
public static void main(String[] args) {
Student obj = new Student(5678654, "Shawn");
System.out.println("The ID: " + obj.getId() + " The Name: " + obj.getName());
// The next line will show the message that length should be between 6 and 8
obj.setID(123456789);
obj.setName("JohnCarlo");
System.out.println("\nThe ID: " + obj.getId() + " The Name: " + obj.getName());
}
}
Here is the output:
it is observed that the id remains unchanged