整数在java中变为负数

时间:2015-10-23 00:26:54

标签: java

为什么每次输入这个值时我的总元素都变成负数? 这是首先输入的5 然后123,130,53,85,100

import java.io.*;
public class Add{
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int element = 1;
        System.out.print("what dimension is your array?: ");
        int dimen = Integer.parseInt (br.readLine());
        if(dimen>10){
            System.out.println("your dimension is too large please try again");
            System.exit(1);
        }
        int[] Array = new int[dimen];
        for(int a = 0; a<dimen; a++){
            System.out.print("what is the value of your dimension?: ");
            int dimen1 = Integer.parseInt (br.readLine());
            Array[a] = dimen1;
            element = element*Array[a];
        }
        System.out.println("The total Value of the element is "+element);
   }
}

为什么答案是这样的? -1386439592

2 个答案:

答案 0 :(得分:2)

每当您将int element = 1;的值乘以123 15990 847470 72034950 7203495000 时,您就会得到

int

但最大值2147483647 可以存储

-1386439592

导致overflowelement

要解决此问题,请考虑将long的类型更改为可包含更大值的内容,例如

  • 9223372036854775807,其中包含的数字最多为BigInteger
  • 或者如果数字更大class Species(object): # immutable. def __init__(self, id): # ... (using id to obtain height and other data from file) def height(self): # ... class Animal(object): # mutable. def __init__(self, nickname, species_id): self.nickname = nickname self.species = Species(id) def height(self): return self.species.height()

答案 1 :(得分:1)

如果不知道Array是什么,我们无法确定,但也许它是从您输入的最后5个数字汇编而来的?

如果是这样,那么你就会遇到整数溢出。 int值在开始环绕之前限制在20亿左右,而128 * 130 * 53 * 85 * 100则超过70亿。

使用long[]Long[]数组代替int[]Integer[]