簡體   English   中英

Java:嘗試了解使用掃描儀從用戶那里獲取輸入

[英]Java: Try to Understand Getting Inputs from Users Using Scanner

我有這個程序,還有一些有關Scanner類的.next()、. nextInt()、. hasNext()和.hasNextInt()如何工作的問題。 預先感謝您的幫助:)

import java.util.Scanner;

public class test {

    public static void main (String[] args) {
    Scanner console = new Scanner(System.in);
    int age;
    System.out.print("Please enter your age: ");
    while (!console.hasNextInt()) {
            System.out.print("Please re-enter your age: ");
            console.next();
        }
    age = console.nextInt();
    System.out.println("Your age is "+age);
    }  
}

1 /第一次執行!console.hasNextInt()時,為什么要求輸入?

我以為首先控制台是空的,所以!console.hasNextInt()為True(空不是int),那么它應該直接從“請輸入您的年齡:”改為“請重新輸入您的年齡:”,但是我的想法似乎是錯誤的。

在此,用戶需要在打印“請重新輸入您的年齡:”之前輸入一些內容。

2 / console.next()的數據類型始終是一個字符串(我嘗試使int s = console.next();它給出了錯誤),那么為什么這不是一個無限循環?

3 /例如,涉及console.next(); ,我輸入21 為什么年齡具有21的值? 我以為是由於console.hasNextInt() ,所以我需要輸入另一個數字,而這個新數字將是age的值。

如果可以使用nextInt()方法將此掃描器輸入中的下一個標記解釋為默認基數中的int值,則java.util.Scanner.hasNextInt()方法將返回true。

當您以非整數輸入開頭時,hasNextInt()將為false,並且您將進入while循環。 然后它將提示您重新輸入年齡。 但是,如果您以整數開頭,則不會進入循環。 您的年齡將被打印。

console.next()表示它將獲取下一個輸入令牌並返回String。 如果您將代碼記為:

String s = null;
while (!console.hasNextInt()) {
    s = console.next();
    System.out.println("You entered an invalid input: " + s);
    System.out.print("Please re-enter your age: ");

}

console.next()用於處理非整數輸入。 現在,如果輸入非整數輸入twenty ,您將看到console.hasNextInt()將為false, console.next()將讀取它。

hasNextInt()等待輸入字符串,然后告訴您是否可以將其轉換為int 考慮到這一點,讓我們來解決您的問題:

第一次執行!console.hasNextInt()時,為什么要求輸入?

因為它會阻塞,直到控制台有一些輸入為止。

console.next()的數據類型始終是字符串(我嘗試使int s = console.next();並給出了錯誤),那么為什么這不是一個無限循環?

因為hasNextInt()在輸入可以轉換int時返回true,例如"21"

例如,涉及console.next(); ,我輸入21 為什么age具有21的值? 我以為是由於console.hasNextInt() ,所以我需要輸入另一個數字,而這個新數字將是age的值。

調用next()並不等待新的輸入,它只是吞下了hasNextInt()測試過的輸入,因此掃描程序可以繼續進行下一個輸入。 它可能是循環中的第一條語句,具有相同的效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM