+ 1

Getters and Setters problem

Hello future programmers, im having difficulties whith the "Student Information System" problem. Cant make it print "Invalid age". Sorry for my bad english. 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; //set the age via Setter System.out.println("Name: " + student.name); System.out.println("Age: " + student.getAge()); } } class Student { public String name; private int age; public int getAge() { //complete Getter return age; } public void setAge(int age) { //complete Setter if(age>0) { this.age= age; } else if(age<0){ System.out.println("Invalid age"); this.age =0; } } }

21st Apr 2021, 8:09 PM
Kevin Sagrista
Kevin Sagrista - avatar
4 Answers
+ 3
It looks your above code is 100% correct, only line 6 is missing which is : student.setAge(age);
4th Oct 2022, 3:30 AM
Mani Raj Adhikari
+ 1
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; //set the age via Setter student.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() { //complete Getter return age; } public void setAge(int age) { //complete Setter if (age>0) { this.age = age; } else if (age<0) { System.out.println("Invalid age"); this.age=0; } } }
28th May 2023, 6:29 PM
Kawinphop Chomnikorn
21st Apr 2021, 8:16 PM
A͢J
A͢J - avatar
0
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(); read.close(); Student student = new Student(); student.name = name; //set the age via Setter student.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() { //complete Getter if(age<0){ System.out.println("Invalid age"); return 0; }else{ return age; } } public void setAge(int age) { //complete Setter if(age<0){ System.out.println("Invalid age"); this.age=0; }else{ this.age=age; } } }
29th Jul 2024, 2:46 PM
Shalini Shalu
Shalini Shalu - avatar