【发布时间】:2013-04-30 21:15:01
【问题描述】:
我正在尝试将 50 个字符的字符串对象解析为整数。我一直在尝试扫描包含 100 行(每行有 50 位数字)的数据文件并计算数字的总和。
每次我尝试将字符串解析为整数时,调用都会引发 NumberFormatException。
这是我到目前为止所拥有的......
{
long totalSum = 0;
ArrayList<Long> list = new ArrayList<Long>();
// Create a new JFileChooser object.
JFileChooser fileChooser = new JFileChooser(
"C:\\Users\\Jon\\workspace\\Project Euler\\src");
// Create an "Open File" Dialog box for
// the user.
fileChooser.showOpenDialog(null);
// Get the file the user selects.
File inputFile = fileChooser.getSelectedFile();
try
{
Scanner in = new Scanner (inputFile);
String nextString = "";
// If the scanner has another token to scan,
// continue with the loop.
while (in.hasNext())
{
// The next string is the next number of characters
// that are not seperated by white space.
nextString = in.next();
try {
ing nextNumber = Integer.parseInt(nextString);
list.add(nextNumber);
} catch (NumberFormatException e) {
System.out.println ("NumberFormatException: " + e.getMessage());
}
}
in.close();
我在尝试解析之前尝试“修剪” String 对象,但没有任何东西可以修剪。我正在扫描的行中没有任何空白。
以下是我尝试扫描并计算以下值的几行:
37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629
我检查了 API 并在 Stack 中进行了相当彻底的搜索。有谁知道如何解决这个问题?
【问题讨论】:
-
我认为这些数字大于整数的大小。尝试 Long.parseLong(nextString) 但我认为您的数字仍然太大,这意味着您应该查看 BigInteger 类。你可以制作一个 BigInteger 的数组列表
标签: java parsing java.util.scanner