2015-06-20 71 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 
} 
相关问题