My assignment is:
- Create a file that has 2 columns of numbers: Distance and Speed.
- Write a class
TravelInfo
which has three pieces of information: Speed, Time, Distance. - The class should also have a method
calcTime()
which calculates the time it will take to reach a destination based on the distance and speed (recall: Time = Distance/Speed) - Write a main program that:
- Creates an ArrayList of
TravelInfo
objects of size 10. - Prompts the user for the name of the file and reads the data into
TravelInfo
objects - Calls the
calcTime()
method on eachTravelInfo
object. - Creates an output file with the data written in the format: Distance, Time, Speed
- Creates an ArrayList of
Every time I run my program I get an error
Exception in thread "main" java.util.NoSuchElementException
Other than this error I think I have done everything right except maybe calling my method, and I still haven't formatted the output file yet (not quite sure how). I can't continue while I get this error.
Here is my main()
method:
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
ArrayList<TravelInfo> list = new ArrayList<>();
System.out.println("What is the name of the file?");
String filename = keyboard.nextLine();
File f = new File(filename);
Scanner inputFile = new Scanner(f);
while(inputFile.hasNext()) {
int s = inputFile.nextInt();
int d = inputFile.nextInt();
int t = inputFile.nextInt();
TravelInfo p = new TravelInfo(s, d, t);
list.add(p);
TravelInfo cls = new TravelInfo(s,d,t);
cls.calcTime(t);
cls.calcTime(s);
cls.calcTime(d);
// System.out.println("Time is " + cls.calcTime(t));
/*for(int i=0; i<list.size(); i++) {
list.get(i).print();
*/ }
for(TravelInfo k : list)
System.out.println(k);
PrintWriter outputFile = new PrintWriter("Data.txt");
outputFile.println(list);
//outputFile.println();
outputFile.close();
}
}
And my TravelInfo
class
public class TravelInfo {
private int speed;
private int distance;
private int time;
public TravelInfo(int s, int d, int t) {
speed = s;
distance = d;
time = t;
}
public int calcTime(int time) {
time = distance/speed;
return time;
}
}