创建一个Java循环,计算用户输入出生年份时的年龄,有什么想法吗?

问题描述 投票:0回答:1

我正在遵守计算机编程的一个项目,并且是编程的新手,我们的教授希望我们'编写一个带循环的程序,该程序可以计算用户的年龄并输出他/她的年龄'。

import java.util.Scanner;
import java.util.Calendar;

public class lisuuh {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int myyear, result;


    do{
        System.out.print("Enter your birth year: ");
        myyear = sc.nextInt();

        result = myyear - year;
    }while(result == result);
    System.out.print("You are "+result+"year/s old.");


    }
}

预期输出:

输入年份:2010

您今年9岁。

java for-loop while-loop do-while jcreator
1个回答
0
投票

您的答案应该像这样改变:

import java.util.Scanner;
import java.util.Calendar;

public class lisuuh {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int myyear, result;
        do {
            System.out.print("Enter your birth year: ");
            myyear = sc.nextInt();
            result = myyear - year;
        } while(result>0); // this line changed
            System.out.println("You are "+result+"year/s old.");//line changed


    }
}
© www.soinside.com 2019 - 2024. All rights reserved.