简体   繁体   中英

Why must you define the scanner inside the if statement?

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 number = 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 number = 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 "number.hasNextInt," I get a compile-time error.

You are taking the value out of the Scanner before you are testing for the next int:

 float year = scanner.nextFloat();

The above line removes the int from the Scanner so hasNextInt() will return false .

Side note: Not sure why you are using hasNextInt() with nextFloat() you should be using Float or Int ...

If the "has"-call is after the "next"-call, the scanner will wait for 2 values.

This is because next___() waits for a value, consumes it, AND then returns it, while has___() waits for a value, pushes it back, AND then returns the presence of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM