![](/img/trans.png)
[英]Why Does The Print Statement “=>” Come after you type in Input For The Scanner
[英]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()
來使用Float
或Int
...
如果“ has”呼叫在“ next”呼叫之后,則掃描儀將等待2個值。
這是因為next___()
等待一個值,使用它,然后返回它,而has___()
等待一個值,將其推回,然后返回它的存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.