簡體   English   中英

Java:將文件中的整數讀入數組

[英]Java: Reading integers from a file into an array

File fil = new File("Tall.txt");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);

int [] tall = new int [100];

String s =in.readLine();

while(s!=null)
{
    int i = 0;
    tall[i] = Integer.parseInt(s); //this is line 19
    System.out.println(tall[i]);
    s = in.readLine();
}

in.close();

我正在嘗試使用文件“Tall.txt”將其中包含的整數寫入名為“tall”的數組中。 它在某種程度上做到了這一點,但當我運行它時,它也會拋出以下異常(:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at BinarySok.main(BinarySok.java:19)

為什么它會這樣做,我該如何刪除它? 在我看來,我將文件作為字符串讀取,然后將其轉換為整數,這並不違法。

你可能想做這樣的事情(如果你在 java 5 及以上)

Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
   tall[i++] = scanner.nextInt();
}

您的文件中必須有一個空行。

您可能希望將 parseInt 調用包裝在“try”塊中:

try {
  tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
  continue;
}

或者在解析之前簡單地檢查空字符串:

if (s.length() == 0) 
  continue;

請注意,通過在循環內初始化索引變量i ,它始終為 0。您應該在while循環之前移動聲明。 (或使其成為for循環的一部分。)

為了比較,這里是另一種讀取文件的方法。 它的一個優點是您不需要知道文件中有多少個整數。

File file = new File("Tall.txt");
byte[] bytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String[] valueStr = new String(bytes).trim().split("\\s+");
int[] tall = new int[valueStr.length];
for (int i = 0; i < valueStr.length; i++) 
    tall[i] = Integer.parseInt(valueStr[i]);
System.out.println(Arrays.asList(tall));

看起來 Java 正在嘗試將空字符串轉換為數字。 在這一系列數字的末尾是否有一個空行?

您可能可以像這樣修復代碼

String s = in.readLine();
int i = 0;

while (s != null) {
    // Skip empty lines.
    s = s.trim();
    if (s.length() == 0) {
        continue;
    }

    tall[i] = Integer.parseInt(s); // This is line 19.
    System.out.println(tall[i]);
    s = in.readLine();
    i++;
}

in.close();

您可能會混淆不同的行尾。 Windows 文件將以回車和換行結束每一行。 Unix 上的某些程序會讀取該文件,就好像它在每行之間有一個額外的空行,因為它將回車視為行尾,然后將換行視為另一行尾。

File file = new File("E:/Responsibility.txt");  
    Scanner scanner = new Scanner(file);
    List<Integer> integers = new ArrayList<>();
    while (scanner.hasNext()) {
        if (scanner.hasNextInt()) {
            integers.add(scanner.nextInt());
        } else {
            scanner.next();
        }
    }
    System.out.println(integers);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM