I am trying to write a program for school. The assignment is to loop and ask the user to enter files. When either a file is not found or the user exits out the loop (in my case, they click cancel on a joptionpane) data for each of the files is output. So far this is my code:
/**
* @param args
*/
public static void main(String[] args) {
// Lists to hold file data
List<String> fileNames = new ArrayList<String>();
List<Integer> numChars = new ArrayList<Integer>();
List<Integer> numWords = new ArrayList<Integer>();
List<Integer> numLines = new ArrayList<Integer>();
String inFile;
while ( (inFile = JOptionPane.showInputDialog("Enter a file name:")) != null) {
// Create new file object instance
File file = new File(inFile);
try {
fileNames.add(inFile); // File name as a string
// Pass file objects
numChars.add( getNumChars(file));
numWords.add( getNumWords(file));
numLines.add( getNumLines(file));
System.out.println("entered try block");
} catch(FileNotFoundException e) {
System.out.println("Could not find file: " + inFile);
// break out the loop and display data
break;
}
} // end while
if (numChars.size() > 0)
showFileData(fileNames, numChars, numWords, numLines);
System.out.println("Program ended");
}
private static void showFileData(List<String> fileNames,
List<Integer> numChars, List<Integer> numWords,
List<Integer> numLines) {
for (int i=0;i<numChars.size();i++) {
System.out.println("Data for: " + fileNames.get(i));
System.out.println("Number of characters: " + numChars.get(i));
System.out.println("Number of words: " + numWords.get(i));
System.out.println("Number of lines: " + numLines.get(i));
System.out.println("-----------------------------------------------");
}
}
private static int getNumLines(File file) throws FileNotFoundException {
int c = 0;
Scanner f = new Scanner(file);
while(f.hasNextLine()) {
c++;
}
return c;
}
private static int getNumWords(File file) throws FileNotFoundException {
int c = 0;
Scanner f = new Scanner(file);
while (f.hasNextLine()) {
String[] w = f.nextLine().split(" ");
c += w.length;
}
return c;
}
private static int getNumChars(File file) throws FileNotFoundException {
Scanner f = new Scanner(file);
int c = 0;
String line;
while(f.hasNextLine()) {
line = f.nextLine();
String[] s = line.split(" ");
for (int i=0;i<s.length;i++) {
c += s[i].length();
}
}
return c;
}
When I run the program, if I press cancel, it exits the loop and displays the stuff at the end like it’s supposed to. If I enter a file that doesn’t exist, it works how it’s supposed to. The only time it doesn’t work is when I enter a file that DOES exist, it doesn’t pop up another input dialog. In fact, it doesn’t seem to enter the try block. Have I set my program up correctly?
You have an infinite loop in
getNumLines(). You need af.nextLine()in the while loop.