0

I just started Java and I am playing around.

I have the following code which I want to count the letter 'e' of your input but the output every time is "0." what am I doing wrong? thanks.

import javax.swing.JOptionPane;
public class JavaApplication6 {
public static void main(String[] args, int z) {
 int y,z = 0;
 String food;
 food = JOptionPane.showInputDialog("Are you curious how many \"e\"s there are in your favorite Food? Then Type your favorite food and I will tell you!");  
       char letter = 'e';


 for(int x = 0; x < food.length();x++){
     if(food.charAt(z)== letter){
         y = y++;
     }
 }
 JOptionPane.showMessageDialog(null, "it has: " + y);
}

}

1 Answers1

1

Since you are using x in your for loop, and iterating through each character in food, instead of food.charAt(z), you should be doing food.charAt(x). Also, you may want to look into how to use increment/decrement operators. Here is some more info on that topic.

I slightly modified your code (mainly formatting), but this should fix your problem:

import javax.swing.JOptionPane;

public class JavaApplication6 {
    public static void main(String[] args) {
        int y = 0;
        char letter = 'e';
        String food = JOptionPane.showInputDialog("Are you curious how many \"e\"s " +
             "there are in your favorite Food? Then Type your favorite food and I " + 
             "will tell you!");  

        for(int x = 0; x < food.length(); x++)
            if(food.charAt(x) == letter)
                y++;

        JOptionPane.showMessageDialog(null, "it has: " + y);
     }
}
Mr Jones
  • 1,188
  • 3
  • 17
  • 33