+ 1

I need to know that how to set input data to object to get the output in class below.

public static void main(String[] args) { Scanner read = new Scanner(System.in); String firstName = read.nextLine(); String secondName = read.nextLine(); int age = read.nextInt(); int roomNumber = read.nextInt(); Customer customer = new Customer(); //set customers data to object here customer.firstName = read.nextLine(); customer.secondName = read.nextLine(); customer.age = read.nextInt(); customer.roomNumber = read.nextInt(); customer.saveCustomerInfo(); } } class Customer { String firstName; String secondName; int age; int roomNumber; //add all necessary attributes here public void saveCustomerInfo() { System.out.println("First name: " + firstName); System.out.println("Second name: " + secondName); System.out.println("Age: " + age); System.out.println("Room number: " + roomNumber); } } My attempt is as above. I'm unable.

7th May 2021, 6:54 AM
Swapnil Kamdi
Swapnil Kamdi - avatar
3 Answers
+ 2
you are scanning everything two times one via main variables and the other through your class variables which is wrong as u must have entered only once in your input stream The below code is correct public static void main(String[] args) { Scanner read = new Scanner(System.in); Customer customer = new Customer(); //set customers data to object here customer.firstName = read.nextLine(); customer.secondName = read.nextLine(); customer.age = read.nextInt(); customer.roomNumber = read.nextInt(); customer.saveCustomerInfo(); } } class Customer { String firstName; String secondName; int age; int roomNumber; //add all necessary attributes here public void saveCustomerInfo() { System.out.println("First name: " + firstName); System.out.println("Second name: " + secondName); System.out.println("Age: " + age); System.out.println("Room number: " + roomNumber); } }
7th May 2021, 8:37 AM
Nikhil Menon
Nikhil Menon - avatar
0
Thank you
7th May 2021, 8:49 AM
Swapnil Kamdi
Swapnil Kamdi - avatar
0
Np
7th May 2021, 9:03 AM
Nikhil Menon
Nikhil Menon - avatar