為什么只列印第二行的資料?據說它會按列列印所有資料,對吧?我在這個java編程中犯了哪一行錯誤?
我做了什么,不會作業:
- 把 for(int i=0; i < cols.length; i );
- 放置 while (sc.hasNextLine())
我所說的以上資訊都給了我這個:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Forensic.main(Forensic.java:28)
import java.io.*;
import java.util.*;
public class Forensic
{
public static void main(String[] args) throws IOException
{
try
{
File fin = new File("Bill.txt");
FileReader fileReader = new FileReader(fin);
BufferedReader bufReader = new BufferedReader(fileReader);
File foutBelow = new File("BelowAmount.txt");
FileWriter writerBelow = new FileWriter(foutBelow);
PrintWriter printBelow = new PrintWriter(writerBelow);
printBelow.println("Payment less than or equal to RM 1000");
printBelow.println("Record\t\tUser ID\t\t\tPayment");
String string = "";
Scanner scan = new Scanner(bufReader);
while((string = bufReader.readLine()) != null)
{
string = scan.nextLine();
String cols[] = string.split(",");
printBelow.println(cols[0] "\t\t\t" cols[1] "\t\t\t\t" cols[2]);
}
System.out.println("Data successfully transfered");
bufReader.close();
printBelow.close();
}
catch (FileNotFoundException fnfE)
{
System.out.println("File not found");
}
catch (IOException ioE)
{
ioE.printStackTrace();
}
}
}
在 Bill.txt 檔案中
1208,236,289.90
1209,221,299.70
1210,236,479.60
1211,236,200.00
1212,221,560.60
1213,289,4000.00
1214,289,235.60
1215,236,280.50
1216,221,100.20
1217,221,2800.30
1218,236,1400.70
1219,289,778.90
1220,289,778.90
1221,236,420.50
1222,277,235.60
1223,277,229.90
1224,236,479.60
1225,221,300.20
1226,289,1400.70
1227,236,479.60
低于金額.txt 的輸出
Payment less than or equal to RM 1000
Record User ID Payment
1209 221 299.70
輸出如上。直接顯示第二行資料。
uj5u.com熱心網友回復:
在 Java 中,有很多方法可以讀取檔案、格式??化其內容并將格式化的內容寫入另一個檔案,但您似乎將它們混合在一起。
下面的代碼顯示了一種方法,它使用 class java.util.Scanner。
(代碼后的注釋。)
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Forensic {
public static void main(String[] args) {
Path source = Paths.get("Bill.txt");
try (Scanner scan = new Scanner(source);
PrintWriter printBelow = new PrintWriter("BelowAmount.txt")) {
printBelow.println("Payment less than or equal to RM 1000");
printBelow.println("Record\t\tUser ID\t\t\tPayment");
while (scan.hasNextLine()) {
String string = scan.nextLine();
String[] cols = string.split(",");
if (cols.length == 3) {
printBelow.printf("%s\t\t\t%s\t\t\t\t%s%n", cols[0], cols[1], cols[2]);
}
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
不要假設您正在閱讀的檔案的內容與您期望的一樣。因此,在上面的代碼中,在呼叫 method 之后split,我檢查以確保從檔案中讀取的行具有預期的格式。
請參閱Oracle 的 Java 教程中的掃描和格式化。
請參閱API 檔案以了解如何創建和使用類java.io.PrintWriter,例如。它有一個接受字串引數的建構式。因此,無需創建 aFile然后 aFileWriter即可創建 a PrintWriter。
我還建議使用try-with-resources來確保關閉程式中使用的所有檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/498095.html
下一篇:R基于行條件的資料框中的不同計算
