gpt4 book ai didi

java - 调用方法从 Scanner 获取变量并将其分配给新变量

转载 作者:太空宇宙 更新时间:2023-11-04 13:56:49 29 4
gpt4 key购买 nike

我在方法调用方面遇到了困难,尤其是在与扫描仪一起使用时。

我得到了一小段代码;

import javax.swing.JOptionPane;
import java.util.Scanner;
import java.util.Calendar; // for date calcs

public class UtilsMS {

// user input methods, by datatype ----------------------------------------

// get an int value
public static int readInt(String prompt)
{
// set up data and objects
Scanner input = new Scanner(System.in);
int data;

// prompt for an input int value
System.out.print(prompt);
data = input.nextInt();

return data;
}

所以我进入我的主客户端 Java 代码并尝试;

public class AgeClientMS
{
public static void main(String [] args)
{
// Declarations
int todayDate, todayCal;
String getMonth = "Enter birth month: ";
String getDay = "Enter birth day: ";
String getYear = "Enter birth year: ";
int data;

// Methods

UtilsMS.readInt(getMonth);
UtilsMS.readInt(getDay);
UtilsMS.readInt(getYear);

//Outputs, Formatting, Display
}
}

据我所知,我意识到我需要使用 UtilsMS 类中的扫描器获取 INT 值,然后重新为其分配另一个值,以便我可以将获取的每个值用于 future 的 SimpleDate 日期。我只是不知道如何重新分配该值。

最佳答案

我想我明白你想做什么。基于您有一个今天日期的字段这一事实,我猜您也在尝试计算该人的年龄。所以我基本上在这段代码中回答了你的问题,并且还用它做了一些我认为你正在尝试做的其他事情。

import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class AgeClientMS
{
public static void main(String [] args)
{
// Declarations
int todayDate, todayCal;
String getMonth = "Enter birth month: ";
String getDay = "Enter birth day: ";
String getYear = "Enter birth year: ";
int data;

// Methods

// UtilsMS returns an integer value which we store in variables.
int birthMonth = UtilsMS.readInt(getMonth);
int birthDay = UtilsMS.readInt(getDay);
int birthYear = UtilsMS.readInt(getYear);

//Outputs, Formatting, Display

Calendar birthCalendar = Calendar.getInstance();
birthCalendar.set(birthYear, birthMonth - 1, birthDay);

Calendar todayCalendar = Calendar.getInstance();

long ageInMilliseconds = todayCalendar.getTimeInMillis() - birthCalendar.getTimeInMillis();
System.out.println("Age In Milliseconds: " + ageInMilliseconds);
System.out.println("Age In Years: " + ((ageInMilliseconds / (24 * 60 * 60 * 1000)) / 365));


SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
Date birthDate = format.parse(birthMonth + "/" + birthDay + "/" + birthYear);
System.out.println("You were born on: " + birthDate);


} catch (ParseException e) {
e.printStackTrace();
}
}
}

关于java - 调用方法从 Scanner 获取变量并将其分配给新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29737632/

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