I am trying to read a text file, and then display the output in another file. I can only read using Scanner. input.txt
3005045 7
3245436 0
7543536 3
8684383 -1
output.txt should be like
ID Number of Bags Total Cost
** ************** **********
customer pays 20.50 per bag if the bag is 4 or less. and pays 15.50 per bag if the bag greater than 4. but if it's 0 or negative number this message should appeared "Error : Wrong Number of Bags" I did this program, but it works only once(reads one line only)
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();
}
}
You don't need that for loop over there. Also, you want to read line by line. Here is quick fix of your code:
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");
while(infile.hasNext()){
ID = infile.nextInt();
int i = infile.nextInt();
if (i <= 0) {
pw.println(ID + "\n\t\tError: Wrong Number of Bags\t\t\t");
} else if (i <= 4) {
total = (80.50) * i;
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
} else {
total = ((80.50) * 4) + ((75.50) * (i - 4));
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
}
}
infile.close();
pw.close();
}
}
Output.txt
ID Number of Bags Total Cost
3005045 7 548.503245436
Error: Wrong Number of Bags
7543536 3 241.508684383
Error: Wrong Number of Bags