Create a Java class called Student with the following details as variables within it. (i) USN (ii) Name (iii) Branch (iv) Phone Write a Java program to create n-Student objects and print the USN, Name, Branch, and Phone of these objects with suitable headings.
1 package program1.student; 2 3 public class Student { 4 private String usn; 5 private String name; 6 private String branch; 7 private String phone; 8 9 public Student(String usn, String name, String branch, String phone) { 10 this.usn = usn; 11 this.name = name; 12 this.branch = branch; 13 this.phone = phone; 14 } 15 16 @Override 17 public String toString() { 18 return "Student [usn=" + usn + ", name=" + name + ", branch=" + branch + ", phone=" + phone + "]"; 19 } 20} 21 22package program1.student; 23 24import java.util.Scanner; 25 26public class StudentDemo { 27 28 public static Student readStudData() { 29 30 Scanner s = new Scanner(System.in); 31 32 System.out.println("USN: "); 33 String usn = s.next(); 34 System.out.println("Name: "); 35 String name = s.next(); 36 System.out.println("Branch: "); 37 String branch = s.next(); 38 System.out.println("Phone: "); 39 String phone = s.next(); 40 41 return (new Student(usn, name, branch, phone)); 42 } 43 44 public static void main(String[] args) { 45 46 Scanner s = new Scanner(System.in); 47 48 System.out.println("How many Students: "); 49 int nStud = s.nextInt(); 50 51 Student[] studs = new Student[nStud]; 52 53 for (int i = 0; i < nStud; ++i) { 54 System.out.println("\nEnter Student - " + (i + 1) + " details one / one"); 55 56 studs[i] = readStudData(); 57 } 58 59 System.out.println("\nStudent Database:"); 60 61 for (int i = 0; i < nStud; ++i) { 62 System.out.println(studs[i]); 63 } 64 65 } 66 67} |
OUTPUT:
How many Students:
2
Enter Student - 1 details one / one
USN: 4BD13CV001
Name: ARJUN
Branch: CIVIL
Phone: 9264921640
Enter Student - 2 details one / one
USN: 4BD15IS010
Name: CHARAN
Branch: IS
Phone: 7592783640
Student Database:
Student [usn=4BD13CV001, name=ARJUN, branch=CIVIL, phone=9264921640]
Student [usn=4BD15IS010, name=CHARAN, branch=IS, phone=7592783640]
No comments:
Post a Comment