Incompatible types - found java.lang.String but expected int, in java
-
11-06-2021 - |
Question
Displays the date 100 days from today, the day you were born, and the date 10,000 days after your birth date. I've done all that, but i want to take it a step further, i want the user to be able to input the number of days from today that he/she wishes to know the date of (if that makes any sense at all...). Here's what the part of the code i'm working on looks like:
public class calendarProjectTest
{
public static void main(String[] args)
{ GregorianCalendar cal = new GregorianCalendar(); //declare today's date
GregorianCalendar myBirthday = new
GregorianCalendar(1990, GregorianCalendar.JUNE, 9); //declare my birthday
System.out.println("Please enter a number greater than 0:");
Scanner keyboard = new Scanner(System.in);
String number = keyboard.next();
int value = number;
cal.add(GregorianCalendar.DAY_OF_MONTH, number);
I'm using Bluej and it says, "incompatible types - found java.lang.String but expected int" I'm at a loss. i don't have any idea what to do. any advise would be great. and yes, i know there are no end brackets.
Solution
Change this:
cal.add(GregorianCalendar.DAY_OF_MONTH, Integer.parseInt(number));
As you can see from the docs, the add()
method needs both parameters as int
.
OTHER TIPS
Use this:
int value = Integer.parseInt(number);
problem lies here
String number = keyboard.next();
int value = number;
instead use :
int value = keyboard.nextInt(); // you will get parsed int value
cal.add(GregorianCalendar.DAY_OF_MONTH, value);
Keyboard.next(); returns a string, not an integer.
so int value = number is trying to assign a string value to an int type. try putting this instead: int value = Integer.parseInt( number );
want more info about GregorianCalendar and http://www.vogella.com/articles/JavaDateTimeAPI/article.html