Need help with program please: getting symbol error
I have an assignment in my intro level programming class to write a program to count the number of times a character occurs in a file. My professor showed us how to write this program in class but I continue to get a missing symbol error on my FileInputStream line. Could someone please tell me how to fix this? Ignore my awful formatting in the program and realize that this is how my professor wants us to write this program. So try to keep it in this mindset. Appreciate the help! Here is my program as of now.
Code :
import java.util.*;
public class Prog7
{
public static void main(String[] args)
{
Scanner keybd = new Scanner(System.in);
String filename;
char ch;
int count;
//Prompt the user for filename.
filename = keybd.next();
count = frequency(ch,filename);
System.out.println("In the file " + filename + ", the character " + ch + " appears " + count + " times.");
}
//Given a character ch and a filename.
//Prints the number of times the character appears
//in the file. Returns the count.
public static int frequency(char ch, String fname)
{
FileInputStream f = new FileInputStream(newFile(fname));
int count;
char nextChar;
count=0;
nextChar=f.read();
while(nextChar != -1)
{if(nextChar==ch)
count++;
nextChar=f.read();
}
f.close();
return count;
}
}
Re: Need help with program please: getting symbol error
Java will force you to initialize all variables before they can be used. I suspect you'll probably want some way that this variable can be changed dynamically by the user, but that doesn't necessarily have to be the case.
Code :
char ch = 'a'; // example
Also, the FileInputStream constructor can possibly throw a FileNotFoundException which must be caught, and the next() method throws a IOException which must be caught. The easiest way to get around this is to make both the frequency and the main methods have declared that they throw an IOException (since FileNotFoundException is a child of IOException)
Code :
public static void main(String[] args) throws IOException
I'm guessing this is a typo, but you need a space here:
Code :
// your code
FileInputStream f = new FileInputStream(newFile(fname));
// correct code
FileInputStream f = new FileInputStream([b]new File[/b](fname));
Also, the read method technically gives back a byte, which Java tries to cast up to an int. To get it to compile, you must put an explicit cast to a char
Code :
nextChar = (int) f.read();