簡體   English   中英

Java為什么將十進制數輸出為Integer?

[英]Why does Java outputs decimal number as Integer?

所以這是我的程序:

// Creates a Scanner object that monitors keyboard input
static Scanner userInput = new Scanner(System.in);

public static void main(String[] args)
{

    System.out.print("How old are you? ");

    int age = checkValidAge();

    if (age != 0)
    {
    System.out.println("You are " + age + " years old");
    }

}

public static int checkValidAge() 
{

    try
    {
        return userInput.nextInt(); // nextInt() receives the user input
    }

    catch (InputMismatchException e)
    {
        userInput.next(); // Skips the last user input and waits for the next
        System.out.print("That isn't a whole number");
        return 0;
    }

}

當我輸入一個帶小數點后三位的數字時,Java將其輸出為整數:

在此處輸入圖片說明

如果我輸入的數字帶有2個或3個以上的小數點,則程序將知道輸入不正確。 那么,為什么它忽略3個小數位並將其作為int輸出呢?

Stream::nextInt從流中讀取一個整數。
2,444是默認語言環境中的整數( 2,444 = 2444 )。

如果要讀取十進制數字,則需要使用Stream::nextDouble或其他合適的方法。

暫無
暫無

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

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