I'm having trouble extracting the information from an external file for a program I'm writing. The program for my class is that I am to write a program that reads in pairs of data (vehicle, Gate number) and outputs the name of the vehicle type, the toll, the factor, and total bill for turnpike use.
Vehicle Type Factor Car Type
1 1.0 Compact Car
2 1.3 Small Car
3 1.6 Mid Size Car
4 2.0 Full size Car
5 2.4 Truck
6 2.7 16 Wheeler
Gate Toll
1 1.35
2 2.00
3 2.50
4 3.25
5 4.10
6 4.8
7 5.50
8 6.00
Ex. Output:
Car Type Base Toll Factor Cost
Compact Car $1.35 1.00 $ 1.35
Small Car $2.50 1.30 $ 3.25
Mid Size Car $4.10 1.60 $ 6.56
Full Size Car $5.50 2.00 $11.00
Truck $2.00 2.40 $ 4.80
16 Wheeler $3.25 2.70 $ 8.78
Compact Car $4.80 1.00 $ 4.80
Small Car $6.00 1.30 $ 7.80
Mid Size Car $1.35 1.60 $ 2.16
Full Size Car $2.50 2.00 $ 5.00
Truck $4.10 2.40 $ 9.84
16 Wheeler $5.50 2.70 $14.85
Compact Car $6.00 1.00 $ 6.00
Small Car $1.35 1.30 $ 1.75
Mid Size Car $2.00 1.60 $ 3.20
Full Size Car $2.50 2.00 $ 5.00
Truck $3.25 2.40 $ 7.80
16 Wheeler $4.10 2.70 $11.07
(What the program should output shown above)
I know how to read the external file, but I'm not sure if extracting and using the information inside the file requires a different series of steps. I don't know if I'm missing something obvious since I'm still a beginner, but I have my basic code with the while loop for the external file:
import java.io.*;
import java.util.*;
public class Prog40
{
public static void main(String[] args) throws IOException
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\Programs\\Prog40\\Prog40.in"));
while(kbReader.hasNext())
{
}
}
}
The file data is this:
1 1
2 3
3 5
4 7
5 2
6 4
1 6
2 8
3 1
4 3
5 5
6 7
1 8
2 1
3 2
4 3
5 4
6 5
I know I can do the rest of the program, but extracting information from the file and using it is still confusing me. Could someone please guide me through utilizing the external file? Any help is greatly appreciated.
What I find the easiest to do is:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))
. Read the file line by line:
String line; while( (line=reader.readLine())!=null){ //do something with the line of text. }
Do it in that way. Your data will be storred in resultCollection.
public class Prog40
{
public static void main(String[] args) throws IOException
{
Scanner kbReader = new Scanner(new File("C:\\Users\\Guest\\Documents\\Programs\\Prog40\\Prog40.in"));
List<String> resultCollection = new ArrayList<String>();
while(kbReader.hasNext())
{
String line = kbReader.nextLine();
resultCollection.add(line);
}
}
}
After getting it in resultCollection you can performe some action on it.
public void someAction(List<String> resCollection){
//do stuff there.
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.