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();
}
}
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.
Okay, I've updated it, but after changing if statement like that it still shows me an error. I've tried also with
Integer.parseInt(skaner.next()) == true
but it's also wrongFor one thing, it is spelled "scanner" with a c.
"skaner" is Scanner in non-english form. That is the way how I called the variable, so it doesn't matter tho
You'll have to catch the exception and handle it separately. I have updated the answer with correct code.
@MXtrocin Your update is still invalid, because
Integer.parseInt()
returns the integer value, not a boolean. What exactly is your problem with using the code in this answer?