I am writing a program that read string and integers from file, then copy the data and write to another file. Data entries should be separated by a space.
My input should and output should follow the following format, the first two set of numbers are string while the others are integers:
123123 242323 09 08 06 44
I get Exception in thread "main" java.util.NoSuchElementException when I run my code, I do not know why
import java.util.Scanner;
import java.io.*;
public class Billing {
public static void main(String[] args) throws IOException {
//define the variables
String callingnumber;
String callednumber;
String line;
int startinghour;
int startingminute;
int endinghour;
int endingminute;
//open input and output files
FileReader freader = new FileReader("BillingData.txt");
BufferedReader inFile = new BufferedReader(freader);
FileWriter fwriter = new FileWriter("BillingOutput.txt");
PrintWriter outFile = new PrintWriter (fwriter);
// set space between the numbers
line=inFile.readLine();
while(line!=null)
{
//creat a scanner to use space between the numbers
Scanner space = new Scanner(line).useDelimiter(" ");
callingnumber=space.next();
callednumber=space.next();
startinghour=space.nextInt();
startingminute=space.nextInt();
endinghour=space.nextInt();
endingminute=space.nextInt();
// writing data to file
outFile.printf("%s %s %d %d %d %d", callingnumber, callednumber,startinghour, startingminute, endinghour, endingminute);
line=inFile.readLine();
}//end while
//close the files
inFile.close();
outFile.close();
}//end of mine
}//end of class
I suspect that the scanner has run out of data in the line - probably because there are less than 6 values in it. To avoid the error you should do something like this:
if (space.hasNextInt()) {
startingHour = space.nextInt();
}