for循环(JAVA)中的条件问题
我和我的朋友们一起学习编程,我们被一些乍一看起来很简单的东西搞得一塌糊涂 基本上,我们有一个只运行一次的for循环。在里面我们得到一些用户输入。然后我们使用一个条件来确定是应该将+1添加到countM(男性计数)还是将+1添加到countF(女性计数) 问题->问题出现在条件上。当用户输入为“F”时,程序应执行countF++(如果需求已满),但是countM++是每一次执行的程序,即使用户输入为F而不是Mfor循环(JAVA)中的条件问题,java,for-loop,conditional,Java,For Loop,Conditional,我和我的朋友们一起学习编程,我们被一些乍一看起来很简单的东西搞得一塌糊涂 基本上,我们有一个只运行一次的for循环。在里面我们得到一些用户输入。然后我们使用一个条件来确定是应该将+1添加到countM(男性计数)还是将+1添加到countF(女性计数) 问题->问题出现在条件上。当用户输入为“F”时,程序应执行countF++(如果需求已满),但是countM++是每一次执行的程序,即使用户输入为F而不是M public static void main(String[] args) {
public static void main(String[] args) {
int countM = 0;
int countF = 0;
int peso;
int estatura;
String sexo;
for (int i = 1; i <= 2; i++) {
if(i == 2){
JOptionPane.showMessageDialog(null, "El nº de chicos aptos es " + countM);
JOptionPane.showMessageDialog(null, "El nº de chicas aptas es " + countF);
break;
}
JOptionPane.showMessageDialog(null, "Teclea los datos del alumno nº "+ i);
estatura = Integer.parseInt(JOptionPane.showInputDialog("Teclea la estatura del alumno (cm)"));
peso = Integer.parseInt(JOptionPane.showInputDialog("Teclea el peso del alumno en kg"));
sexo = JOptionPane.showInputDialog("Teclea el sexo del alumno (M o F)");
if(sexo == "F"){
if(estatura>160 && peso>60){
countF++;
}
}
else{
if(estatura>170 && peso>70){
countM++;
}
}
}
}
publicstaticvoidmain(字符串[]args){
int countM=0;
int countF=0;
国际比索;
国际遗产;
弦乐六重奏;
对于(整数i=1;i 160和比索>60){
countF++;
}
}
否则{
如果(estatura>170和比索>70){
countM++;
}
}
}
}
使用sexo.equalsIgnoreCase(“f”)代码>而不是sexo==“f”
并添加一个检查,确保用户只输入M或F,否则它仍将使用CountM++
使用sexo.equalsIgnoreCase(“F”)代码>而不是sexo==“f”
并添加一个检查,确保用户只输入M或F,否则它仍然会执行CountM++
在Java中比较字符串的方法是sexo.equals(“F”)
。在Java中,'=='比较字符串对象(或任何对象)的引用,而不是内容。在Java中比较字符串的方法是sexo.equals(“F”)
。在java中,“==”比较字符串对象(或任何对象)的引用,而不是内容。