I need help with a part of a java program. This part of the program reads a file
ID: 3753696 • Letter: I
Question
I need help with a part of a java program. This part of the program reads a file "flooring.dat" and stores the data in variables: orderID (string), size (character - S, M, L), tileColor (string - black, white, grey), squareinchprice (float), quantity (int)
It reads one line of .dat, does a few operations with the variables (seperate part of my program), and then reads the next line of .dat, repeating until there is no new line.
example .dat format (can have more or less orders/lines):
24434 M black .35 1
7112784 L white 0 2
6239 L grey .03 10
Question: How do I read one line and save the data into variables, looping through the .dat line by line?
Explanation / Answer
The following code shows you how you can create Order objects which you can later process. Please do rate the answer if it helped. Thank you
ProcessOrder.java
-----------------
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class Order
{
private String orderId;
private char size;
private String color;
private double price;
private int quantity;
public Order(){
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public char getSize() {
return size;
}
public void setSize(char size) {
this.size = size;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String toString(){
return "ID: "+ orderId +", Size: " + size + ", Color: " + color+ ", Price: " + price +", Qty: " + quantity;
}
}
public class ProcessOrder {
public static void main(String[] args) {
try {
Scanner infile = new Scanner(new File("flooring.dat"));
while(infile.hasNext()){
Order ord = new Order();
ord.setOrderId(infile.next());
ord.setSize(infile.next().charAt(0));
ord.setColor(infile.next());
ord.setPrice(infile.nextDouble());
ord.setQuantity(infile.nextInt());
//now process order
System.out.println(ord);
}
infile.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
output
------
ID: 24434, Size: M, Color: black, Price: 0.35, Qty: 1
ID: 7112784, Size: L, Color: white, Price: 0.0, Qty: 2
ID: 6239, Size: L, Color: grey, Price: 0.03, Qty: 10
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.