0

Setter & getter in JAVA, please help me to solve this bullshit

import java.util.Scanner; class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); String name = read.next(); int age = read.nextInt(); Student student = new Student(); student.name = name; student.setAge(age); //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() { return age; } public void setAge(int newAge) { if (newAge < 0) { System.out.println("Invalid age"); this.age = 0; } else { this.age = age; } } } I cant solve the final code in getter and setter, because the compiler always shows NO OUTPUT. If you have a solution, please sent it

13th Feb 2024, 12:51 PM
Ayanokoji Kiyotaka
Ayanokoji Kiyotaka - avatar
4 Réponses
+ 3
Ayanokoji Kiyotaka your argument is newAge. why are you using this.age = age; //???? shouldn't this be this.age = newAge; public void setAge(int newAge) { if (newAge < 0) { System.out.println("Invalid age"); this.age = 0; } else { this.age = newAge; } }
13th Feb 2024, 1:34 PM
Bob_Li
Bob_Li - avatar
+ 1
Ayanokoji Kiyotaka it's ok to use + to concatenate strings and ints inside println. But always remember that numbers are implicitly converted to strings if you have a string in the + chain. so if you have: int a = 20; int b = 24; System.out.println("Total = " + a + b); will print out: Total = 2024 while: System.out.println( a + b); will print out: 44
13th Feb 2024, 4:29 PM
Bob_Li
Bob_Li - avatar
+ 1
When using this.age you have to think of it as a pointer. private int age <<< public void setAge(int age){<<< this.age = age;<<< } Theyre all lowercased
14th Feb 2024, 3:29 PM
Andre Richmond
Andre Richmond - avatar
0
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); String name = read.next(); int age = read.nextInt(); Student student = new Student(); student.setName(name); student.setAge(age); //set the age via Setter System.out.println("Name: " + student.getName()); System.out.println("Age: " + student.getAge()); } } class Student { public String name; private int age; public int getAge() { return age; } public String getName() { return name; } public void setName(String name){ this.name= name; } public void setAge(int age) { if (this.age < 0) { System.out.println("Invalid age"); } else { this.age = age; } }
14th Feb 2024, 3:28 PM
Andre Richmond
Andre Richmond - avatar