2 回答
TA贡献1804条经验 获得超8个赞
name具有"Isabella Cruz F"在索引0和阵列的其余部分是nullS,SO name1是null在第二次迭代。从第一个循环中取出第二个循环。
for (int i = 0; i < name.length; i++) {
//...
}
for (String name1 : name) {
//...
}
您也可以只使用一个循环并在那里获取数据
int maleCount = 0;
int femaleCount = 0;
for (int i = 0; i < name.length; i++)
{
int index = i;
System.out.println("Enter name of applicant and gender:");
System.out.println("M for male and F for female");
name[index] = myVar.nextLine();
if (name[index].contains("M")) {
maleCount++;
}
else if (name[index].contains("F")) {
femaleCount++;
}
}
System.out.println("NUMBER OF MALE: " + maleCount);
System.out.println("NUMBER OF FEMALE: " + femaleCount);
TA贡献1833条经验 获得超4个赞
有几个问题。首先是有一个嵌套的 for 循环。我看到您首先填充 String 数组,然后对其进行迭代以检查计数。你真的只需要一个循环。其次是您正在检查字符串是否包含“M”或“F”,如果人名包含该字符串(Ex Joanna M Smith F),这可能会出现问题。您只需要检查最后一个字符。
import java.util.Scanner;
public class Problem5 {
public static void main (String [] args)
{
Scanner myVar = new Scanner (System.in);
int b = 1000;
String [] names = new String [b];
int maleCount = 0;
int femaleCount = 0;
/*enter name and gender of applicants*/
for (int i=0; i<name.length; i++)
{
System.out.println("Enter name of applicant and gender:");
System.out.println("M for male and F for female");
String line = myVar.nextLine();
names[i] = line;
// check if the line passed in is a M or F
if (line.substring(line.length()-1).equals("M"))
{
maleCount++;
}
if (line.substring(line.length()-1).equals("F"))
{
femaleCount++;
}
System.out.println("NUMBER OF MALE: "+maleCount);
System.out.println("NUMBER OF FEMALE: "+femaleCount);
}
}
}
添加回答
举报