Java 用于搜索特定信函帮助的代码
我刚开始学Java,现在正在到处玩 我有以下代码,我想计算输入的字母“e”,但每次输出都是“0”。我做错了什么?谢谢Java 用于搜索特定信函帮助的代码,java,string,loops,if-statement,charat,Java,String,Loops,If Statement,Charat,我刚开始学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 curiou
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);
}
import javax.swing.JOptionPane;
公共类JavaApplication6{
公共静态void main(字符串[]args,int z){
int y,z=0;
串食;
food=JOptionPane.showInputDialog(“你想知道你最喜欢的食物中有多少个\“e\”?然后键入你最喜欢的食物,我会告诉你的!”);
字符字母='e';
对于(intx=0;x
}既然您在for循环中使用了
x
,并在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);
}
}
import javax.swing.JOptionPane;
公共类JavaApplication6{
公共静态void main(字符串[]args){
int y=0;
字符字母='e';
String food=JOptionPane.showInputDialog(“你想知道有多少个\“e\”吗?”+
“你最喜欢的食物中有吗?然后键入你最喜欢的食物和我”+
“我会告诉你的!”;
对于(intx=0;x
y=y++
应该是y++
,或者++y
,或者y=++y
删除了我的答案,因为rohit发布的链接有更好的解释main
的参数列表中的intz
不属于那里;你应该移除它<代码>公共静态void main(字符串[]args)。只有代码的答案很少有用。如果里面有一些文字,可能会很有用。