繁体   English   中英

为什么必须在if语句中定义扫描器?

[英]Why must you define the scanner inside the if statement?

以下代码为何起作用:

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.");
        }
    }
}

但是这段代码没有:

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.");
        }
    }
}

似乎您必须先定义扫描程序,以便if语句可以知道它要检查的内容。 否则,它如何知道要检查的内容?

但是,当我将scanner.nextFloat行放在if语句之外时,它将编译,但在用户键入输入时会在运行时卡住。 而且,如果我将行放在外面并将if语句更改为“ number.hasNextInt”,则会收到编译时错误。

在测试下一个int之前,您需要从Scanner中获取值:

 float year = scanner.nextFloat();

上一行从Scanner删除了int ,因此hasNextInt()将返回false

旁注:不知道为什么要使用带有nextFloat() hasNextInt()来使用FloatInt ...

如果“ has”呼叫在“ next”呼叫之后,则扫描仪将等待2个值。

这是因为next___()等待一个值,使用它,然后返回它,而has___()等待一个值,将其推回,然后返回它的存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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