(first day of trying to learn java)
I have a basic code which takes user input and checks if it is and integer, a double, or a string (in that order). Currently, if the input is integer or string, it works perfectly but if it is a double/decimal, the code for the string "if" statement is also triggered. If i switch the places of the "if" statements for the double and the integer, the integer one starts to trigger the string statement instead of the double. I tried placing the string statement at the very top so nothing is above it but this just makes it so that the string statement overrides the statement below it.
For some reason, instead of using "if" statement for the string, using "else" works (and also removing the statement all together results in the program running as expected) but i want to understand why this is happening for future projects.
import java.util.Scanner;
public class second {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter a number real quick: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
System.out.println("U owe me $" + numberEntered);
}
if (userInput.hasNextDouble()) {
double doubleEntered = userInput.nextDouble();
System.out.println("U owe me $" + doubleEntered);
}
if (userInput.hasNextLine()) {
String stringEntered = userInput.nextLine();
System.out.println("'" + stringEntered + "'" + " ain't a number dummy");
}
}
}
I expect "U owe me $2.1" when I put in 2.1 but i instead get "U owe me $2.1 '' ain't a number dummy"
*edit: deleted closing } when deleting a comment