Java 练习 - 家庭成员



我写了一个程序,给出了家庭成员的类型。例如:0-3岁 - 婴儿,3-12岁 - 儿童,12-31岁,年轻人等。为此,我使用了if

Scanner keybord = new Scanner(System.in);
int age = klavye.nextInt();
age = klavye.nextInt(); 
age = klavye.nextInt();
int count = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0;
System.out.println("Enter the age of the family member : ");
if (age >= 0 && age <= 3);
    count++;
if(age >=4 && age <= 12);
    count1++;
if (age >= 13 && age <= 30);
    count2++;
if (age >= 31 && age <= 49);
    count3++;
if (age >=50 && age <= 120);
    count4++;
System.out.println(count+" "+ count3); // this to try to work "count" 

当我写 3 次"49"时,我想要显示计数 3 = 3,但只显示 1。

你需要一个循环,并将变量的初始化移到循环之外。

int count = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0;
do {
    ...
} while(...);

我已经稍微修改了你的代码:

  1. Adedd 循环多次接受输入。我在循环中编码了 3
  2. 用于构造if..else if,而不是if。此更改不是强制性的,而是最佳做法。
  3. 从 if 语句中删除了;

Scanner keybord = new Scanner(System.in);

int count = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0;
for (int i = 0; i < 3; i++) {
System.out.println("Enter the age of the family member : ");
int age = klavye.nextInt();
if (age >= 0 && age <= 3)
    count++;
else if(age >=4 && age <= 12)
  count1++;
else if (age >= 13 && age <= 30)
  count2++;
else if (age >= 31 && age <= 49)
  count3++;
else if (age >=50 && age <= 120)
  count4++;
}
System.out.println(count+" "+ count3);

最新更新