I'm trying to read integers from a text file, but I want to handle the first line differently from the rest, and take the following lines and loop some calculations. Below is my file reader, my question is about the next part, however this may provide some context.
public class main
{
BufferedReader in;
public main() throws FileNotFoundException
{
System.out.println("please enter the name of the text file you wish you import. Choose either inputs or lotsainputs. Nothing else");
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
System.out.println("You have loaded file: \t\t"+filename);
in = new BufferedReader(new FileReader(file));
Scanner inputFile = new Scanner(file);
String element1 = inputFile.nextLine().toUpperCase();
try
{
while ((element1 = in.readLine()) != null)
{
System.out.println("Line to process:\t\t"+element1);
myCalculations(element1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
The first text file look like this:
200 345
36
The second text file look like this:
200 345
36
45
36
21
Here is the method called:
public static void myCalculations(String s)
{
String[] items = s.split(" ");
int[] results = new int[100];
String errorMessage = "that's a wrap!";
for (int i = 0; i < items.length; i++)
{
try {
int stuff = Integer.parseInt(items[i]);
results[i] = stuff;
}
catch (NumberFormatException nfe) {
System.out.println(results);
System.out.println(errorMessage);
}
}
int health = result[0];
int power = result[1];
int days = result[2];
some calculations....
returns new health and power of the car.
same calculations but results[3] as the time period
returns new health and power of car
etc....
}
The method parses the integers, puts them into the results[] array.
Lets say the first two numbers of the text file are health and power of a car. Each proceeding number are days between races. Each race there is deterioration of the of the car and engine, the amount of deterioration is a factor of days in between each race.
I have used results[3][4]&[5] and hard code the deterioration and print the results and it works, but its pretty crap. How would I improve this method? I'm copy and pasting the 'calculations'. How do I take the first line, then put the following lines in a separate loop?
ideally, the number of days in the text file could vary. ie, there could be 5 races, or there could be 3 and the program will handle both cases.
try something like
result for file:
is