我正在嘗試讀取文本文件,然後在另一個文件中顯示輸出。 我只能使用掃描儀閱讀。 input.txt中java程序使用掃描儀讀取並打印到文本文件
3005045 7
3245436 0
7543536 3
8684383 -1
output.txt的應該是像
ID Number of Bags Total Cost
** ************** **********
客戶支付20.50每袋如果包是4以下。 和每袋支付15.50如果袋大於4 但如果它是0或負數此消息應該出現「錯誤:袋裝打錯了」我做這個節目 ,但它只能一次(讀取一行只)
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Bags {
public static void main(String []args) throws IOException {
FileInputStream fileinput = new FileInputStream("input.txt");
FileOutputStream fileoutput = new FileOutputStream("output.txt");
Scanner infile = new Scanner(fileinput);
PrintWriter pw = new PrintWriter(fileoutput);
double total = 0, line = 0;
int bags = 0, ID = 0, count = 0;
pw.println("ID\t\tNumber of Bags\t\t\tTotal Cost");
for(int i = bags; i >= 0; i++, count++){
ID = infile.nextInt();
i = infile.nextInt();
if (i <= 0){
pw.println(ID + "\tError: Wrong Number of Bags\t\t\t");
break;
}
else if (i <= 4){
total = (80.50)*i;
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
break;
}
else {
total = ((80.50)*4)+((75.50)*(i-4));
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
break;
}
}
infile.close();
pw.close();
}
}
什麼input.txt中的列代表什麼?我也有點擔心'i> = 0; i ++',因爲它看起來像一個無限循環,除非'i'總是在後面設置爲<0 – rath
@jpw如果OP沒有在任何地方使用nextLine(),所以消耗行分隔符沒有問題。即使每個數字都放在'nextInt()'的新行中,系統也會毫無問題地讀取它們。 – Pshemo