gpt4 book ai didi

java - 如何计算当年和出生年份的差值

转载 作者:行者123 更新时间:2023-11-29 08:21:07 24 4
gpt4 key购买 nike

我在编程课上有一个项目,我必须通过当前年份减去他们的出生年份来找到某人的年龄。然而,当我写代码时,它一直给我“50.0minus50.0=0.0”的答案。

import java.util.Scanner;

public class ageMath {
String firstName;
static int currentYear;
static int birthYear;
double mathEquation;'

Scanner lookAtKeyboard = new Scanner(System.in);

public void getFirstName() {
System.out.println("What is your first name");
firstName = lookAtKeyboard.nextLine();
}

public void getCurrentYear() {
System.out.println("What is the current year");
currentYear = lookAtKeyboard.nextLine().charAt(0);
}

public void getBirthYear() {
System.out.println("What is your birth year");
birthYear = lookAtKeyboard.nextLine().charAt(0);
}

public void doMath(double birthYear, double currentYear) {
mathEquation = currentYear - birthYear;
System.out.println(currentYear +"minus"+ birthYear + "=" + mathEquation);
}

public static void main (String[] args) {
ageMath calculator = new ageMath();
calculator.getFirstName();
calculator.getCurrentYear();
calculator.getBirthYear();
calculator.doMath(currentYear,birthYear);
}
}

我应该怎么做才能解决这个问题?

最佳答案

对于 int,您必须使用 nextInt()java string charAt() 方法返回给定索引号处的 char 值 .不适合你现在的场景。

 import java.util.Scanner;

class Main {




String firstName;

static int currentYear;

static int birthYear;

double mathEquation;

Scanner lookAtKeyboard = new Scanner(System.in);


public void getFirstName()
{
System.out.println("What is your first name");
firstName =lookAtKeyboard.nextLine();
}

public void getCurrentYear() {
System.out.println("What is the current year");
currentYear =lookAtKeyboard.nextInt();
}

public void getBirthYear() {
System.out.println("What is your birth year");
birthYear =lookAtKeyboard.nextInt();
}

public void doMath(double birthYear, double currentYear) {
mathEquation = currentYear - birthYear;
System.out.println(currentYear +"minus"+ birthYear + "=" +mathEquation);

}



public static void main (String[] args) {

Main calculator = new Main();
calculator.getFirstName();
calculator.getCurrentYear();
calculator.getBirthYear();
calculator.doMath( currentYear,birthYear);

}


}

工作 link (我只是更改了类名,以便它可以在 fiddle 上工作)

关于java - 如何计算当年和出生年份的差值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58155732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com