+ 1

Setters and Getters Java

If age is under 0,you have to print a messages "Invalid option", Age : 0 and name else print just the name and age. I tried by my own, but it works only for age<0.So if someone know to solve and wants to help, I will be very thankful. import java.util.Scanner; class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); String name = read.nextLine(); int age = read.nextInt(); Student student = new Student(); student.name = name; Student sa = new Student(); sa.setAge (age); System.out.println("Name: " + student.name); System.out.println("Age: " + student.getAge()); } } class Student { public String name; private int age; public int getAge() { return age; } public void setAge(int age) { if (age<0){ System.out.println("Invalid age"); this.age = 0; }else{ this.age = age; } } }

18th Mar 2021, 1:28 AM
Zotta
Zotta - avatar
1 ответ
18th Mar 2021, 1:44 AM
Vadivelan