Matt G Matt G - 1 day ago 5
Java Question

Write a program to count the number of times that the character "a" appears anywhere in the file JavaIntro.txt.

I am trying to figure out how to count all of the numbers into 1 counter this counts the number of 'a' from each line and displays each line I want to know how to count all of them onto one line.

import java.io.*;
import java.util.Scanner;


public class CountTheNumberOfAs {
public static void main(String[] args)throws IOException
{

String fileName = "JavaIntro.txt";
String line = "";
Scanner scanner = new Scanner(new FileReader(fileName));
try {

while ( scanner.hasNextLine() ){
line = scanner.nextLine();
int counter = 0;

for( int i=0; i<line.length(); i++ ) {
if( line.charAt(i) == 'a' ) {
counter++;

}


}

System.out.println(counter);
}
}
finally {

scanner.close();


}}}

Answer

You need to move the counter outside of the while loop. (same for the print):

int counter = 0;
while ( scanner.hasNextLine() ){
// ...
}
System.out.println(counter);
Comments