0

我刚开始使用 Java,我正在玩。

我有以下代码,我想计算输入的字母“e”,但每次的输出都是“0”。我究竟做错了什么?谢谢。

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);
}

}

4

1 回答 1

1

由于您x在 for 循环中使用,并遍历food, 而不是 中的每个字符food.charAt(z),因此您应该使用food.charAt(x). 此外,您可能想了解如何使用递增/递减运算符。是有关该主题的更多信息。

我稍微修改了您的代码(主要是格式化),但这应该可以解决您的问题:

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);
     }
}
于 2013-10-10T18:14:53.300 回答