Warm tip: This article is reproduced from stackoverflow.com, please click
if-statement java

Why if condition "(skaner.next() != int)" highlights as wrong?

发布于 2020-03-31 22:54:57

I wanna make a condition if somebody input a word the program will return "That is a string" if it is an integer the program will return "That is an integer ". What's wrong with my if condition ?

package folder;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
    Scanner skaner = new Scanner(System.in);

    while (skaner.hasNext()){
        if (skaner.next() != int) {
            System.out.println("That is a string" + skaner.next());
        }
        else {
            System.out.println("That is an integer " + skaner.next());
        }
    }
    skaner.close();


    }
}
Questioner
MXtrocin
Viewed
61
Abhinav Goyal 2020-02-02 13:24

Here skaner.next() will return a String object whereas int is a primitive data type and therefore both are not comparable. To check if token returned by skaner.next() is an int or not, you can use Integer.parseInt(skaner.next()) which converts String to int and throws a NumberFormatException if input is not a valid integer.

package folder;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
    Scanner skaner = new Scanner(System.in);

while (skaner.hasNext()){
    String x = skaner.next();
    try {
        int y = Integer.parseInt(x);
        System.out.println("That is an integer " + y);
    }
    catch(NumberFormatException e) {
        System.out.println("That is a string " + x);
        }
    }
    skaner.close();
    }
}

Check this link for reference.