Java Eclipse Lets say I want to use instance variables (birthdate,day,month,year
ID: 3609760 • Letter: J
Question
Java EclipseLets say I want to use instance variables (birthdate,day,month,year).
I want the user to enter their day month and year components oftheir birthdate and save that into the corresponding instancevariable day. month and year.
How do I code the instance variable birthdate to use the input fromday,month and year and store it in a format likemonth-day-year?
Do I use a method or is it possible to store day month and yearinputs within the instance variable birthdate?
What I'm trying to achieve is to be able to call upon the birthdateinstance variable so this code will be possibleSystem.out.println("The Birthdate is:" + birthdate);
Explanation / Answer
import java.util.Scanner; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int day, month, year; System.out.print("Please enter the day: "); while(!scan.hasNextInt()) {System.out.print("Invalid input! Please enter an integer:"); String garbage = scan.next(); } day = scan.nextInt(); System.out.print("Please enter the month: "); scan= new Scanner(System.in); while(!scan.hasNextInt()) {System.out.print("Invalid input! Please enter an integer:"); String garbage = scan.next(); } month = scan.nextInt(); System.out.print("Please enter the year: "); scan= new Scanner(System.in); while(!scan.hasNextInt()) {System.out.print("Invalid input! Please enter an integer:"); String garbage = scan.next(); } year = scan.nextInt(); String birthdate = month + "-" + day +"-" + year ; System.out.println("The birthdate is: " + birthdate); } while(!scan.hasNextInt()) {System.out.print("Invalid input! Please enter an integer:"); String garbage = scan.next(); } month = scan.nextInt(); System.out.print("Please enter the year: "); scan= new Scanner(System.in); while(!scan.hasNextInt()) {System.out.print("Invalid input! Please enter an integer:"); String garbage = scan.next(); } scan= new Scanner(System.in); while(!scan.hasNextInt()) {System.out.print("Invalid input! Please enter an integer:"); String garbage = scan.next(); } while(!scan.hasNextInt()) {System.out.print("Invalid input! Please enter an integer:"); String garbage = scan.next(); } year = scan.nextInt(); String birthdate = month + "-" + day +"-" + year ; System.out.println("The birthdate is: " + birthdate); }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.