import java.util.Scanner; class person{ String name; int age; float salary; Scanner…
- User
import java.util.Scanner; class person{ String name; int age; float salary; Scanner sc=new Scanner(System.in);
public void get_value(){ System.out.println("Enter the name:"); this.name=sc.nextLine();
System.out.println("Enter the age:"); this.age=sc.nextInt(); System.out.println("Enter the salary:"); this.salary=sc.nextFloat();} public void print_value(){ System.out.println("Detail of person"); System.out.println("Name"+name); System.out.println("age"+age); System.out.println("salary"+salary); } } class main{ public static void main(String[] args){ person p1=new person();
p1.get_value(); p1.print_value();} }
- Assistant
Your Java code snippet is almost correct but has a common issue related to the use of
Scannermethods (nextIntandnextFloat) when reading mixed types of inputs (numbers followed by String). When you read a number (int or float) and then try to read a String, the newline character left over from entering the number causes an issue. Thesc.nextLine()for reading the name immediately after reading numbers withsc.nextInt()orsc.nextFloat()does not wait for user input because it reads the newline character.To solve this, add an extra
sc.nextLine()after eachsc.nextInt()andsc.nextFloat()to consume the leftover newline character. I've also made some minor tweaks for improved readability and corrected the output formatting.Here's the corrected and slightly improved version of your code:
import java.util.Scanner; class Person { String name; int age; float salary; Scanner sc = new Scanner(System.in); public void getValues() { System.out.println("Enter the name:"); this.name = sc.nextLine(); System.out.println("Enter the age:"); this.age = sc.nextInt(); sc.nextLine(); // Consume the leftover newline System.out.println("Enter the salary:"); this.salary = sc.nextFloat(); sc.nextLine(); // Consume the leftover newline } public void printValues() { System.out.println("Detail of the person:"); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } } public class Main { public static void main(String[] args) { Person p1 = new Person(); p1.getValues(); p1.printValues(); } }Key Changes:
- Changed class name from
persontoPersonto follow Java naming conventions. - Changed method names from
get_valuetogetValuesandprint_valuetoprintValuesfor consistency with Java naming conventions. - Added
sc.nextLine()after usingnextInt()andnextFloat()to consume the newline characters. - Formatted the print statements in
printValuesfor clearer output. - Changed the class
maintoMainto adhere to Java convention where classes start with a capital letter.
Remember, class names in Java are typically written in PascalCase, and method names in camelCase, to improve readability and maintain standard coding practices.
- Changed class name from