PDA

View Full Version : Need help finishing program!!!


bebelew
02-10-2005, 01:08 AM
I need help finishing this program. What the program is suppose to do is ask the user to input a file and any character they choose. Then the computer is suppose to go through the file and count how many times that character is in the file. This is what I have so far but I need help finishing it.

import java.io.*;

public class SPA4
{
public static void main(String[] args) throws IOException
{
String filename, //File name
line, //To read a line of text
character; //The character
int number = 0, //for number of characters found
location; //for locating the character in the file

// Make the objects necessary for console input
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(reader);

//Get the filename
System.out.print("Enter the filename: ");
filename = keyboard.readLine();

//Open the file
FileReader freader = new FileReader(filename);
BufferedReader inputFile = new BufferedReader(freader);

//Get the character
System.out.print("Enter the character: ");
character = keyboard.readLine();

//Read the first line in the file
line = inputFile.readLine();

location = line.indexOf(character);


//Close the file
inputFile.close();

//Print the final output
System.out.print(number);

}
}

lext
02-10-2005, 01:23 AM
Technically you shouldn't ask that here, because this is Javascript forum (and your question is about Java). But I know Java a little, so ... Assuming you're opening the file and reading the character correctly. Then instead of this:

//Read the first line in the file
line = inputFile.readLine();
location = line.indexOf(character);

Do this:

number = 0;
while ((line = inputFile.readLine()) != null) {
int start = 0;
int pos;
while ((pos = line.indexOf(character, start)) >= 0) {
start = pos;
number++;
}
}

At the end of this number will be the count you need.

bebelew
02-10-2005, 02:10 AM
oh sorry i wasnt really paying attention to where i was posting because i was in a hurry but thanks for the help