我知道這可能不是編碼這種最有效的方式,但這是我迄今爲止的工作,直到數字變得非常大。代碼應從文件中讀取2個數字,例如「052」和「61」。然後應該將第一個數字從最大到最小排序,使數字儘可能大,第二個數字從最小到最大,使其儘可能小。 (520 & 16)然後它打印二者的差,在這種情況下:504解析大數時NumberFormatException?
的數字中的兩個是「3827367453723784675745843783623672348745389734268374687」和「1682761482512674172712635416571265716235471625176235741」。從最大到最小,最小到最大的數字排序工作正常,但是當我嘗試將其解析爲一個整數時,會拋出一個NumberFormatException
。我想,因爲數量太大,無法存儲到int
,所以我嘗試解析爲Long
,但導致了相同的錯誤。
我所做的只是將數字讀作String
,然後將String
數組存儲在一個單獨的索引中。然後我做了一個int
數組,我幾乎有相同的數組,除了整數形式而不是String
。然後我排序了int
陣列。然後我又創建了另一個String
來存儲新的排序號碼,然後我試圖解析String
,這就是拋出異常的地方。
有什麼建議嗎?
import java.io.*;
import java.util.*;
import java.text.*;
import static java.lang.System.*;
public class BigDif
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner (new File ("BigDif.dat"));
int numRuns = scan.nextInt();
scan.nextLine();
for (int i = 0; i < numRuns; i++)
{
String firstNum = scan.nextLine();
String secondNum = scan.nextLine();
String[] firstNum2 = new String[firstNum.length()];
String[] secondNum2 = new String[secondNum.length()];
int[] firstNum3 = new int[firstNum.length()];
int[] secondNum3 = new int[secondNum.length()];
int big = 0;
int notBig = 0;
String firstNum4 = null;
String secondNum4 = null;
int firstNum5 = 0;
int secondNum5 = 0;
for (int j = 0; j < firstNum.length(); j++)
{
firstNum2[j] = Character.toString(firstNum.charAt(j));
}
for (int j = 0; j < secondNum.length(); j++)
{
secondNum2[j] = Character.toString(secondNum.charAt(j));
}
for (int j = 0; j < firstNum2.length; j++)
{
firstNum3[j] = Integer.parseInt(firstNum2[j]);
secondNum3[j] = Integer.parseInt(secondNum2[j]);
}
Arrays.sort(firstNum3);
Arrays.sort(secondNum3);
for (int m = 0; m < firstNum3.length; m++)
{
if (m == 0)
firstNum4 = (Integer.toString(firstNum3[m]));
else
firstNum4 = (Integer.toString(firstNum3[m]))+ firstNum4;
}
for (int m = 0; m < secondNum3.length; m++)
{
if (m == 0)
secondNum4 = (Integer.toString(secondNum3[m]));
else
secondNum4 += (Integer.toString(secondNum3[m]));
}
firstNum5 = Integer.parseInt(firstNum4); //the exception is thrown here
secondNum5 = Integer.parseInt(secondNum4);
if (firstNum5 >= secondNum5)
{
big = firstNum5;
notBig = secondNum5;
}
else
{
big = secondNum5;
notBig = firstNum5;
}
out.println(big - notBig);
}
}
}
'1682761482512674172712635416571265716235471625176235741'遠遠超出了Integers的範圍。 – SudoRahul