我是一名新的java程序员,正在研究先前的建议,以生成一个计算器,该计算器可以接受1-365的整数并给出月份和日期。我不知道如何将每个月解决为单独的变量。完全陷入困境。任何帮助将不胜感激。
import java.util.Scanner;
public class principal {
public static void maxn(String[] args) {
Scanner input = new Scanner(System.in);
int x = 0;
int date;
if (x < 30) {
month = "January";
date = x;
System.out.println(month + " " + day);
} else
x += 31;
if (31 < x < 58){
String month = "February";
day -= x;
if (31 < x < 58 < 89) {
month = "March"
day -= x;
if (31 < x < 58 < 89 < 120) {
month = "April"
day -= x;
if (31 < x < 58 < 89 < 120 < 150) ;
{
month = "May"
day -= x;
if (31 < x < 58 < 89 < 120 < 150 < 180) ;
{
month = "June"
day -= x;
if (31 < x < 58 < 89 < 120 < 150 < 180 < 211) {
month = "July"
day -= x;
if (31 < x < 58 < 89 < 120 < 150 < 180 < 211 < 242) {
month = "August"
day -= x;
if (31 < x < 58 < 89 < 120 < 150 < 180 < 211 < 242 < 273) {
month = "September" day -= x;
if (31 < x < 58 < 89 < 120 < 150 < 180 < 211 < 242 < 273 < 303) {
month = "October" day -= x;
if (31 < x < 58 < 89 < 120 < 150 < 180 < 211 < 242 < 273 < 303 < 334) {
month = "November"
day -= x;
if (31 < x < 58 < 89 < 120 < 150 < 180 < 211 < 242 < 273 < 303 < 365) {
month = "December"
day -= x;
}
}
}
}
答案 0 :(得分:0)
根据我对你的理解,你会想要这样的事情:
int yourInt = 325; // YOUR NUMBER HERE, BETWEEN 1 and 365
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2013); //depending on the year you want
cal.set(Calendar.DAY_OF_YEAR, yourInt);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date myDate = sdf.parse(sdf.format(cal.getTime()));
System.out.println("date : " + myDate.toString());
System.out.println("month : " + (cal.get(Calendar.MONTH) + 1)); //+1 because January is 0
System.out.println("day of month : " + cal.get(Calendar.DAY_OF_MONTH));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
改变年份当然会改变你获得的价值。
使用325作为整数,您将获得此输出:
月份:11 每月的一天:21
日期:星期四,11月21日14:12:57 2013年
答案 1 :(得分:0)
以下是两种完全不同的方式来做你想做的事。第一个假设是当年(即闰年),第二个假设它不是闰年。
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
while (!line.isEmpty())
{
int i = Integer.parseInt(line);
// way 1
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_YEAR, i);
System.out.println(c.get(Calendar.DAY_OF_MONTH) + " " +
DateFormatSymbols.getInstance().getMonths()[c.get(Calendar.MONTH)]);
// way 2
String[] months = {"JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"};
int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
int j = 0;
while (i > days[j])
i -= days[j++];
System.out.println(i + " " + months[j]);
line = br.readLine();
}
}