Why does the code below work:
import java.util.Scanner;
public class WholeNumber
{
public static void main(String[] args)
{
System.out.println("Please enter a number:");
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt())
{
float year = scanner.nextFloat(); //The if statement is testing THIS scanner value.
System.out.println("The number you entered is an integer.");
}
else
{
System.out.println("The number you entered is not an integer.");
}
}
}
But this code doesn't:
import java.util.Scanner;
public class WholeNumber
{
public static void main(String[] args)
{
System.out.println("Please enter a number:");
Scanner scanner = new Scanner(System.in);
float year = scanner.nextFloat(); //But when I put the scanner out here, it doesn't work??
if (scanner.hasNextInt())
{
System.out.println("The number you entered is an integer.");
}
else
{
System.out.println("The number you entered is not an integer.");
}
}
}
It would seem like you would have to define the scanner first so the if statement could know what it was checking. Otherwise, how does it know what it is trying to check?
When I put the scanner.nextFloat line outside the if statement, though, it will compile but get stuck during run-time when the user is typing in input. And if I put the line outside and change the if statement to "year.hasNextInt," I get a compile-time error.
Aucun commentaire:
Enregistrer un commentaire