java索引不同_将字符串拆分为不同的数组索引Java?

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.Scanner;

public class main {

public static void main(String args[]) {

// Man you should look onto doing your

// homework by yourself, ijs.

// But here it goes, hope i make myself clear.

Scanner input = new Scanner(System.in);

System.out.println("Enter date of birth (MM/DD/YYYY):");

String DOB;

DOB = input.next();

//

int age;

// You need to know when it is today. Its not 2013 forever.

java.util.Calendar cal = java.util.Calendar.getInstance();

// ^ The above gets a new Calendar object containing system time/date;

int cur_year = cal.get(Calendar.YEAR);

int cur_month = cal.get(Calendar.MONTH)+1; // 0-indexed field.

// Cool we need this info. ill skip the day in month stuff,

// you do that by your own, okay?

SimpleDateFormat dfmt = new SimpleDateFormat("MM/dd/yyyy");

int bir_year;

int bir_month;

try {

// If you wanna program, you must know that not all functions

// will exit as it's intended. Errors happen and YOU should deal with it.

// not the user, not the environment. YOU.

Date d = dfmt.parse(DOB); // This throws a parse exception.

Calendar c = Calendar.getInstance();

c.setTime(d);

bir_year = c.get(Calendar.YEAR);

bir_month = c.get(Calendar.MONTH)+1; // 0-indexed field;

age = cur_year - bir_year;

// Well, you cant be a programmer if you dont think on the logics.

if(cur_month < bir_month ) {

age -= 1;

// If the current month is not yet your birth month or above...

// means your birthday didnt happen yet in this year.

// so you still have the age of the last year.

}

// If code reaches this point, no exceptions were thrown.

// and so the code below wont execute.

// And we have the variable age well defined in memory.

} catch(ParseException e) {

// But if the date entered by the user is invalid...

System.out.println("The date you typed is broken bro.");

System.out.println("Type a date in the correct format MM/DD/YYYY and retry.");

return; // Got errors? tell the program to quit the function.

}

// Well now we can say to the user how old he is.

// As if he/she didnt know it ^^'

System.out.println(String.format("You are %d years old", age));

// **Not tested.

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值