我刚刚开始使用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);
}
}
答案 0 :(得分:1)
由于您在for循环中使用x
,并且在food
而不是food.charAt(z)
中迭代每个字符,因此您应该food.charAt(x)
。此外,您可能想要了解如何使用递增/递减运算符。 Here是关于该主题的更多信息。
我稍微修改了你的代码(主要是格式化),但这应该可以解决你的问题:
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);
}
}