Question

Here is how far I've done.

try
   {
      Scanner keyb = new Scanner(System.in);
      System.out.print("Enter the name of the input file-> ");
      String inFileName = keyb.next();
      System.out.print("Enter the name of the output file-> ");
      String outFileName = keyb.next();            
      ArrayList<Time> roster = new ArrayList<Time>();
      Scanner fileIn = new Scanner(new File(inFileName)); 
      while (fileIn.hasNext())
      {
         int hours = fileIn.nextInt();
         int minutes = fileIn.nextInt();
         String meridian = fileIn.next();
         roster.add(new Time(hours,minutes,meridian));
      }
      fileIn.close();

Basically, what I have to do is read 'appointment.txt' file that has all different time that is in 11:30 a.m. form to sort it in order and save it different file name. But because of colon(:) in between hour and minutes, my while loop can't read time correctly and make error. What would make my while loop working?

Was it helpful?

Solution

Your while-loop is not correctly working because you check for fileIn.hasNext(), but afterwards use fileIn.nextInt() and fileIn.next() in different ways.

What you probably want to use is:

while (fileIn.hasNextLine()) {
    String line = fileIn.nextLine();
    String[] bigParts = line.split(" ");
    String[] timeParts = bigParts[0].split(":");
    roster.add(new Time(
        Integer.parseInt(timeParts[0]), 
        Integer.parseInt(timeParts[1]), 
        bigParts[1]
    ));
}

This reads the file line by line, then takes the line it has read. Following it splits the text up in three parts, first by (blank), then by : (colon).

UPDATE: Added Integer.parseInt() as it was originally done aswell.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top