0

How to store data in objects JAVA

import java.util.Scanner; public class Main { 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 customer's data to object here // —->> what do I need to add here thx !! customer.saveCustomerInfo(); } } class Customer { //add all necessary attributes here String firstName; String secondName; int age; int roomNumber; 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); } }

30th Jan 2021, 6:02 PM
zer0x0
zer0x0 - avatar
3 Answers
+ 2
A different approach would be to use a constructor to initalize all your instance variables //This goes into the class under your variables Customer(String firstName,String secondName,int age,int roomNumber){this.firstName=firstName; this.secondName=secondName; this.age=age; this.roomNumber=roomNumber;}; Then pass all your variables to the constructor from the main method Customer customer = new Customer(firstName, secondName, age, roomNumber); then in main call your methods like so customer.saveCustomerInfo(); //this will print everything you passed into the constructor
30th Jan 2021, 10:28 PM
D_Stark
D_Stark - avatar
+ 2
Add set-methods to your Customer-class. public void SetAge(int ageInYears) { age = ageInYears; } Customer customer1 = new Customer() customer1.SetAge(30)
30th Jan 2021, 6:23 PM
Lisa
Lisa - avatar
0
D_Stark thx so much i get it !
10th Feb 2021, 12:51 AM
zer0x0
zer0x0 - avatar