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

时间:2015-04-20 00:42:24

标签: java java.util.scanner

我正在努力使用方法调用,特别是在与Scanner一起使用时。

我给了这段小代码;

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值,然后重新分配另一个值,以便我可以使用我抓到的每个值未来的SimpleDate日期。 我只是无法弄清楚如何重新赋值。

1 个答案:

答案 0 :(得分:0)

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

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();
        }
    }
}