2015-06-20 65 views
5

鑑於以下輸入:如何爲BigInteger分配一個非常大的數字?

4534534534564657652349234230947234723947234234823048230957349573209483057 
1232400

我試圖通過以下方式將這些值分配給BigInteger

public static void main(String[] args) { 

     Scanner sc = new Scanner(System.in); 
     BigInteger num1 = BigInteger.valueOf(sc.nextLong()); 
     sc.nextLine(); 
     BigInteger num2 = BigInteger.valueOf(sc.nextLong()); 

     BigInteger additionTotal = num1.add(num2); 
     BigInteger multiplyTotal = num1.multiply(num2); 

     System.out.println(additionTotal); 
     System.out.println(multiplyTotal); 
    } 

的第一個值是邊界較長的數字之外,所以我得到以下異常:線程「main」 java.util.InputMismatchException

例外:對於輸入字符串 : 「4534534534564657652349234230947234723947234234823048230957349573209483057」

我假設的BigInteger需要一個長型的使用與valueOf()方法(如統計編號here)。我如何將超大數字傳遞給BigInteger?

回答

2

閱讀作爲一個字符串的數量巨大。

public static void main(String[] args) 
{ 
    Scanner in = new Scanner(System.in); 
    String s = in.nextLine(); 
    BigInteger num1 = new BigInteger(s); 

    s = in.nextLine(); 
    BigInteger num2 = new BigInteger(s); 

    //do stuff with num1 and num2 here 
} 
相關問題