Write a program to create a class Student2 along with two method getData (), printData () to get the value through argument and display the data in printData. Create the two objects s1, s2 to declare and access the values from class STtest.
CODE:
import java.util.Scanner;
class Student2 {
private String name;
private int age;
// Method to set data
public void getData(String name, int age) {
this.name = name;
this.age = age;
}
// Method to print data
public void printData() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class STtest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Creating objects of Student2 class
Student2 s1 = new Student2();
Student2 s2 = new Student2();
// Getting data for first student
System.out.println("Enter name for student 1:");
String name1 = scanner.nextLine();
System.out.println("Enter age for student 1:");
int age1 = scanner.nextInt();
scanner.nextLine(); // Consume newline character
// Setting data for first student
s1.getData(name1, age1);
// Getting data for second student
System.out.println("Enter name for student 2:");
String name2 = scanner.nextLine();
System.out.println("Enter age for student 2:");
int age2 = scanner.nextInt();
scanner.nextLine(); // Consume newline character
// Setting data for second student
s2.getData(name2, age2);
// Printing data for both students
System.out.println("Details of student 1:");
s1.printData();
System.out.println("\nDetails of student 2:");
s2.printData();
scanner.close();
}
}
- Define a class Student2 with private instance variables name and age.
- Define a method getData in the Student2 class that takes name and age as arguments and sets the instance variables accordingly.
- Define a method printData in the Student2 class that prints the name and age of the student.
- Define a class STtest.
- Inside the STtest class:
- Create a Scanner object to read input from the user.
- Create two objects s1 and s2 of the Student2 class.
- Prompt the user to enter the name and age for the first student.
- Read the name and age entered by the user for the first student and set the data using the getData method of s1.
- Prompt the user to enter the name and age for the second student.
- Read the name and age entered by the user for the second student and set the data using the getData method of s2.
- Print the details of both students using the printData method.
- Close the Scanner object.
- End of the program.