Java练习 - 家庭成员

时间:2017-05-12 11:12:57

标签: 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”时,我想显示count3 = 3,但只显示1。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我稍微修改了你的代码:

  1. Adedd循环多次输入。我已经在循环中训练了3个。
  2. 使用if..else if构造,而不是if。此更改不是强制性的,而是最佳做法。
  3. 从if语句中删除;
  4. 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);