【问题标题】:assign enum value to a string based on scanner input in java根据java中的扫描仪输入将枚举值分配给字符串
【发布时间】:2025-11-24 07:10:01
【问题描述】:

好的,我对 java 和编码很陌生,我有这个任务,我必须接受用户输入,这将是月、日和年,然后将月乘以日并将其与一年中的最后两位数字来检查它是否是一个神奇的日子。如果用户只使用数字作为输入,我完成了这个,我想尝试做另一个程序,用户输入月份(例如四月(不是 4)),我想看看程序是否可以检查枚举,检查 April 及其值,并将其值分配给 String 月份,然后我将其转换为 int。对不起,如果我的解释很混乱,但我已尽我所能解释了,如果您对某些事情感到困惑,请随时询问。

到目前为止,这是我的代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package magicadvanced;
import java.util.Scanner;
/**
 *
 * @author yfernandez
 */
public class MagicAdvanced {
    public enum Months{
        January(1),February(2),March(3),April(4),May(5),June(6),July(7),August(8),September(9),October(10),November(11),December(12);

        private int value;

        Months(int value){
            this.value = value;
        }


        public int valueInt(){
            return value;
        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner ls=new Scanner(System.in);
        String month,year,yrTwo;
        int day,yearInt;
        System.out.println("Please enter a month.");
        month = ls.next();
        System.out.println("Please enter a day.");
        day = ls.nextInt();
        System.out.println("Please enter the year.");
        year = ls.next();
        yrTwo = year.substring(2,4); //getting last two characters of the string year
        yearInt = Integer.valueOf(yrTwo);// converting last two character of the string year into an integer
        System.out.println(yearInt*2);//this is a just a test code to check if my conversion to integer works, will remove when program is done

    }
}

【问题讨论】:

标签: java string enums int


【解决方案1】:

我的建议是几乎永远不要尝试为时间单位创建自定义枚举。 Java API 已经提供了处理日期所需的所有工具。特别是。 Java 8,带来了显着的改进。您应该查看 thisthis 等资源,以了解 Java 日期时间 API 的主要功能。

以下代码 sn-p 让您了解如何处理月份。

Month month = Month.valueOf("FEBRUARY");

System.out.println(month.getValue());
// output: 2
System.out.println(month.getDisplayName(TextStyle.FULL, Locale.UK));
// output: February

如果你想解析一个代表日期的字符串,你应该使用应该使用DateTimeFormatter,例如显示here

【讨论】:

    【解决方案2】:

    是的,您需要解析字符串输入并将其转换为月份常量的枚举值

    Months x = Months.valueOf("JAnuary")
    

    将 x 初始化到 1 月...

    那么获取的值与你所做的相同:

    int val = x.getValue()
    

    然后你可以用 int 做所有你需要的事情。

    【讨论】: