I'm just starting out in java, and I am totally stumped on this assignment. I have to make a program where the user selects a single character and then a file.

The program is then supposed to check each character in the file, and output how many times that character shows up.

Here is the code I have written.

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

public class LetterCount
{
	public static void main (String[]args) throws IOException
		{
			char lookUp;
			String input;
			String fileName;
			Scanner kB = new Scanner(System.in);
			int tracker = 0;
			
			
			/** Introduction*/
			System.out.println("Welcome to the Letter Master 9000.");
			System.out.println("Please enter a character you would like to count.");
			
			/** users defined character they want to look up*/
			input = kB.nextLine();
			
			/** grabbing the file name*/
			System.out.println("Please enter the location of the file you would like to use:");
			fileName = kB.nextLine();
			
			/** opening the file*/
			System.out.println("I will now examine this file.");
			File file= new File(fileName);
			Scanner inputFile = new Scanner(file);
			
			/** Loop created to find and track the user defined character*/
			while (inputFile.hasNext())
			{
				String line = inputFile.nextLine();
				
				
					if (line == input) 
					{
					tracker = tracker++;
					System.out.println("yes"); //this is used to verify it is working; it isn't :(
					}
				
				}
				inputFile.close();
			System.out.println(tracker);
				
			}
		}

Recommended Answers

All 3 Replies

Can you explain what your problem is?

How are you looking at each character on the line read from the file for the desired character? Look at the String class for methods to get individual characters from the String.
You will need a loop to look at each character in the String from the first to the last one.

You should add an id to the printed output to tell the user what it means:
System.out.println("Nbr chars found=" + tracker);

The problem is that the loop I created at line 32 is suppose to look for the character. every time I run this program the tracker returns a value of zero.

My problem is that I do not know why this loop wouldn't look at the individual characters.

why this loop wouldn't look at the individual characters

There is NO code there to look at any characters.
Try debugging your code by Printing out every line that is read in the loop to show that the program is reading the file OK.

Also print out the value of input to make sure you have good data there.

Use the equals method to test if the contents of two Strings are the same. The == operator does NOT test the contents of objects.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.