简体   繁体   English

如何比较一个整数和一个长?

[英]How to compare an Integer with a long?

I am trying to check if a long integer is greater than the INTEGER.MAX value but it's not working. 我试图检查一个长整数是否大于INTEGER.MAX值,但它不起作用。 It's very straight forward so I am just wondering if there is some problem with comparing an Integer object with a long as I have done because otherwise I don't know what the problem is. 这是非常直接的所以我只是想知道将Integer对象与我所做的长对象进行比较是否有问题,因为否则我不知道问题是什么。 At the moment when the nextTotal value exceeds INTEGER.MAX, it kicks into negative numbers instead of printing the error message. 在nextTotal值超过INTEGER.MAX时,它会输入负数而不是打印错误消息。

public Integer initialValue=0;

int amount = Integer.parseInt(amountStr);
        System.out.println("Received from client: " + amount);

        long nextTotal=amount+initialValue;
            if((nextTotal>Integer.MAX_VALUE)||    (nextTotal<Integer.MIN_VALUE)){
                System.out.println("Error: Integer has not been added as the total exceeds the Maximum Integer value!");
                out.flush();
            }  

            else{
                initialValue+=amount;
                out.println(initialValue); //server response
                System.out.println("Sending total sum of integers to the client:"+initialValue);
                out.flush();
                }
            }

The problem is that you have added two int s, but they haven't been promoted to long yet, so it overflows before being converted to a long , and of course an int can never be greater than Integer.MAX_VALUE . 问题是你已经添加了两个int ,但它们还没有被提升为long ,所以它在转换为long之前溢出,当然int永远不会大于Integer.MAX_VALUE It will only get converted to a long upon assignment, which is after the addition. 它只会在转移后转换为long转换。

Convert to a long before the addition, with a cast. 在添加之前转换为很long ,使用强制转换。

long nextTotal = (long) amount + initialValue;

Since you don't really want to use a long value, I would normally do the check like this: 既然你真的不想使用long值,我通常会做这样的检查:

int amount = Integer.parseInt(amountStr);
if (amount > (Integer.MAX_VALUE - initialValue)) 
  throw new IllegalArgumentException("Amount exceeds maximum value");
initialValue += amount;

In other words, check whether the amount will overflow before adding, and throw an exception (or send an error message or whatever is appropriate for your application) instead of proceeding normally. 换句话说,在添加之前检查金额是否会溢出,并抛出异常(或发送错误消息或适合您的应用程序的任何内容)而不是正常进行。

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

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