In: Computer Science
QUESTION
Write the main while loop for a Java program that processes a set of data as follows:
Each line of the input consists of 2 numbers representing a quantity and price. Your loop should:
1. Read in the input
2. Calculate the tax. Tax will be 8.875% of price and will only be applicable if price is more than 110. Calculate the new price which is the price plus tax.
3. Calculate the final price by multiplying quantity by the new price.
4. Keep a running total of all prices
5. Count the number of lines read in.
E.C. Use input files.
Code:
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
int count = 0;
try{
File file_obj = new File("data.txt");
Scanner myReader = new Scanner(file_obj);
//it will iterate till last line in file
while (myReader.hasNextLine()) {
//it will split line into array of string
String[] data = myReader.nextLine().split("\\s");
//get quantity and price from file
int qua = Integer.valueOf(data[0]);
double price = Float.valueOf(data[1]);
double final_price;
//add tax to price if price is greater than 110
if (price > 110)
price = price + ((price*8.875)/100);
//count final price
final_price = qua * price;
//print final price of n product
System.out.println("New price of "+(count+1)+"th product is : "+String.format("%.2f", final_price));
count++;
}
myReader.close();
}catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
//print number of read from file
if (count==0)
System.out.println("\nThere are currently no record found in file.");
else
System.out.println("\nNumber of line read is : "+count);
}
}
Output: