Mufasa King
Mufasa King

Reputation: 1

Error:incomparable types: String cannot be converted into int

import java.util.Scanner;

public class Name {

public static void main(String args[]) {

    Scanner in = new Scanner(System.in);
    String userName;
    int userAge;

    System.out.println("What is your full name?");
    userName = in.nextLine();

    System.out.println("What is your age?");
    userAge = in.nextLine();

    System.out.println("You're " + userName + " and you are " + userAge + "   years old");
   }
}

This error keeps popping up and i can't find a mistake. Plz help. I am a newbie and i have done my research on this issue. I couldn't find an issue and i have been working over this code for a good week. I want to rip my hair out!!

Upvotes: 0

Views: 467

Answers (2)

Nitin Dandriyal
Nitin Dandriyal

Reputation: 1607

One more way of doing it is:

userAge = Integer.parseInt(in.nextLine().trim());

Java is a strongly typed language, so you cannot assign a one type to another type without typecasting. In this case in.nextLine() returns a String which can't be assigned directly to int datatype

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85799

userAge is an int and you're using in.nextLine() to assign a value to it. Scanner#nextLine returns a String, which is incompatible with int. USeScanner#nextInt instead:

userAge = in.nextInt();
in.nextLine();

Upvotes: 3

Related Questions