簡體   English   中英

JVM為什么返回此整數?

[英]Why Does The JVM Return This Integer?

我已經做了一個非常簡單的數字舍入應用程序,因為我是一個初學者,可能會有一些錯誤,需要進行一些調試,我們可以繼續進行下去,但這不是我在這里的原因。 每當我輸入大於“ int”的容量的整數時,它要么返回“ -1”,要么返回一個非常大的小數字(它是負數,因此更遠離零),例如“ -572589576”。 我想知道JVM返回原因以及原因。 我的程序的代碼如下所示:

import java.util.Scanner;

public class NumberRounder {
private static Scanner userInput2;

public static void main(String[] args) {

    System.out.println("--- Number Rounder ---");

    Scanner userInput = new Scanner(System.in);
    System.out.println("The number you enter will round it to the nearest value.");
    System.out.print("Enter any decimal number: ");

    if (userInput.hasNextDouble()) {
        System.out.println("\nCalculating...");
        System.out.println("Number Rounding...");
        double chosenNumber = userInput.nextDouble();
        int roundedNumber = (int) Math.round(chosenNumber);
        if (roundedNumber == -1) {
            System.out.println("\nAn ERROR occured.");
            System.out.println("That number is too large for our servers. Sorry for the inconvenience.");
            System.exit(0);
        }
        System.out.println(chosenNumber + " has been rounded to " + roundedNumber);
    } else if (!(userInput.hasNextDouble())) {
        System.out.println("\nThat is an illegal response...");
        userInput2 = new Scanner(System.in);
        System.out.println("\nThe number you enter will round it to the nearest value.");
        System.out.print("Enter any decimal number between 1-10: ");
        double chosenNumber = userInput2.nextDouble();
        int roundedNumber = (int) Math.round(chosenNumber);
        System.out.println(chosenNumber + " has been rounded to " + roundedNumber);
    } else {
        System.out.println("Something wrong happened...");
    }
}
}

我已經解決了何時返回“ -1”的問題,但是我仍然不知道如何完全解決此問題。 這就是為什么我在這里問一個問題:為什么JVM返回諸如隨機數之類的東西?

您將double (64位)強制為int ,因此結果值被截斷,並且您看到了這些“隨機”(盡管它們不是隨機的)值。 你應該用一個long為您提供的數字額外的空間。

每當我輸入大於“ int”值容量的整數時

您期望從中得到什么? 例外?

它不會在那里。 Java剛剛從MAX_VALUE轉到MIN_VALUE

你試一試:

    System.out.println(Integer.MAX_VALUE + 1);
    System.out.println(Integer.MIN_VALUE);

並查看其打印內容。

PS。 那就是數字符號如何以int值的實際二進制格式表示。

暫無
暫無

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

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