我有一个需要转换为整数的long值.当我使用强制转换时,时间整数值给出一个负值,这是不期望的.但是当我使用该intValue()方法时Long,会出现预期的结果.
我想知道cast和using intValue()方法的区别
铸造实例
int days = (int) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));
intValue示例
int days = ((Long) ((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24))).intValue();
编辑:更详细说明示例以显示减值而不会出现溢出,如评论中所示.在转换之前,结果是27.当转换时,值变为-22.但是如果使用intValue方法,结果是27.
码
System.out.println("nextDeliveryDate = " + nextDeliveryDate);
System.out.println("nextDeliveryDate.getTime() = " + nextDeliveryDate.getTime());
System.out.println("expectedDeliveryDate = " + expectedDeliveryDate);
System.out.println("expectedDeliveryDate.getTime() = " + expectedDeliveryDate.getTime());
System.out.println("nextDeliveryDate.getTime() - expectedDeliveryDate.getTime() = " + (nextDeliveryDate.getTime() - expectedDeliveryDate.getTime()));
System.out.println("(nextDeliveryDate.getTime() - expectedDeliveryDate.getTime()) / (1000 * 60 * 60 …Run Code Online (Sandbox Code Playgroud) 可能重复:
使用BigInteger进行diffucilty
import java.math.BigInteger;
public class KillerCode{
public static void main(String[]args){
BigInteger sum=null;
for(int i=1;i<=1000;i++){
sum=sum+Math.pow(i, i);
System.out.println(sum);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行此代码时,会出现以下错误消息.
对于参数类型BigInteger,double,运算符+未定义.
我怎么解决这个问题?谢谢.
public static void gramstoAtoms()
{
System.out.println("Enter Amount of grams");
Scanner keyboard = new Scanner(System.in);
long x = keyboard.nextLong();
System.out.println("Enter Unit Grams");
long y = keyboard.nextLong();
long result = x/y;
long answer = result*60200000000000000000000;
System.out.println(answer + "Atoms");
}
Run Code Online (Sandbox Code Playgroud)
如何更改此代码,以便我不会得到一个整数太长的错误?
这是我的代码:
public class sample {
public static void main(String []args) throws Exception {
System.out.println("Enter from file:");
BufferedReader br=new BufferedReader(new FileReader("C:\\Users\\KK\\A Key.txt"));
String currentline;
while((currentline=br.readLine())!=null){
System.out.println(currentline);
}
BigInteger a = new BigInteger(currentline);
System.out.println(a);
}
Run Code Online (Sandbox Code Playgroud)
我想从文本文档中读取,从字符串转换为大整数,我试过这个但是我得到一个运行时错误,如何将String转换为相应的大整数Ascii值.
由于某种原因,我的val变量在while循环中没有增加.有什么原因,为什么它没有这样做?val.add(BigInteger.ONE);
import java.math.*;
public static void main(String[] args) {
/* Variables */
BigInteger PQ = new BigInteger("17");
BigInteger E = new BigInteger("7");
BigInteger val = new BigInteger("2");
/* Find the PRIME factors of PQ */
while (PQ.compareTo(BigInteger.ONE) == 1) { // while the first value is greater
if (PQ.mod(val).equals(BigInteger.ZERO)) {
System.out.print(val + " ");
} else {
val.add(BigInteger.ONE);
}
}
}
Run Code Online (Sandbox Code Playgroud) 我在Java应用程序中使用int作为PK,现在它已达到max int值(20亿),即使在DB中它也可以存储比它更多的数字.但是java int只能容纳大约20亿.
我无法将int更改为long以与DB对齐.因为这是巨大的努力.
除此之外,有人有任何办法吗?