Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculating age with scanner function doesnt work
    text
    copied!<p>first of all, I want to inform everyone that I just started to learn Java on the university. So please forgive me for any mistakes that I make as a newbie.</p> <p>Basically what I want to achieve with this code is to calculate someone's age using the Scanner function. Someone enters their date of birth (in this format YYYY-MM-DD) and my code calculates their age. </p> <p>The code is not working, because I think the 3rd line: <strong>String dob = input.nextInt();</strong> is wrong written and cannot be recognised by the code lines underneath it.</p> <p>if I change that line into <strong>String dob = "1988-11-29";</strong> it works, but then my scanner function has no use. </p> <p>Can someone help me with this? Thanks in advance!</p> <pre><code> Scanner input = new Scanner(System.in); System.out.println("Enter your DOB pls"); String dob = input.nextInt(); int yearDOB = Integer.parseInt(dob.substring(0, 4)); int monthDOB = Integer.parseInt(dob.substring(5, 7)); int dayDOB = Integer.parseInt(dob.substring(8, 10)); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy"); Date date = new Date(); int thisYear = Integer.parseInt(dateFormat.format(date)); dateFormat = new SimpleDateFormat("MM"); date = new java.util.Date(); int thisMonth = Integer.parseInt(dateFormat.format(date)); dateFormat = new SimpleDateFormat("dd"); date = new java.util.Date(); int thisDay = Integer.parseInt(dateFormat.format(date)); int age = thisYear-yearDOB; if(thisMonth &lt; monthDOB){ age = age-1; } if(thisMonth == monthDOB &amp;&amp; thisDay &lt; dayDOB) { age = age-1; } System.out.println("The age of user is : " + age); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload