i SIMPLY DON\'T UNDERSTAND WHAT I AM SUPPOSED TO DO, PLEASE EXPLAINIF YOU CAN HE
ID: 3615451 • Letter: I
Question
i SIMPLY DON'T UNDERSTAND WHAT I AM SUPPOSED TO DO, PLEASE EXPLAINIF YOU CAN HELP ME OUT!- Implement (i.e., write the body of) the following method,countLines, that, given a String parameter, thename of a file, counts and returns the number of lines of text inthe corresponding file.
public static int countLines(String fileName) throws IOException
public static int countLines(String fileName)
2. Implement a newversion of the countLines method that catches the possibleIOException exception and outputs an error messageif such an exception is raised.
public static int countLines(String fileName)
public static int countLines(String fileName)
Explanation / Answer
1. public static int countLine(String fileName) throw IOException{ Scanner inputFile = new Scanner("filename.txt"); int counter = 0; while(inputFile.hasNext()){ inputFile.nextLine(); //eats the whole line counter++; //increments line counter } inputFile.close(); return counter; } 2. Same concept but surround with try/catch public static int countLine(String fileName) { try { Scanner inputFile = new Scanner("filename.txt"); int counter = 0; while(inputFile.hasNext()){ inputFile.nextLine(); //eats the whole line counter++; //increments line counter } inputFile.close(); return counter; } catch(IOException e){ e.printStackTrace(); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.