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

时间:2013-01-31 01:55:38

标签: java arrays string java.util.scanner

我正在尝试将字符串拆分为不同的数组索引。此字符串来自用户输入(通过java.util.Scanner),并被加载到String变量中。如何将字符串中的输入拆分为不同的数组索引?

另外,如何将DOB隐含的数学函数作为int

这是我的代码:

import java.util.Scanner;

public class main {
    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter date of birth (MM/DD/YYYY):");
        String DOB;
        DOB = input.next();
        int age = 0;
        age = 2013 - DOB - 1;
        int age2 = 0;
        age2  = age + 1;
        System.out.println("You are " + age + " or " + age2 + " years old");
    }
}

4 个答案:

答案 0 :(得分:5)

String[] parts = DOB.split("/");
int months = Integer.parseInt(parts[0]);
int days = Integer.parseInt(parts[1]);
int years = Integer.parseInt(parts[2]);

然后在计算中使用years代替DOB

更好的是,使用new Calendar()来获取今天的确切日期,并与之进行比较。

答案 1 :(得分:2)

使用DateTimeFormat中显示的Parse Date String to Some Java Object将您的字符串解析为DateTime对象,然后访问成员。

DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime dateTime = format.parseDateTime(DOB);

这使用Joda Time library

或者,您可以以类似的方式使用SimpleDateFormat,将其解析为Date对象。

答案 2 :(得分:0)

我注意到你正在使用键盘输入来识别字符串。如果用户没有输入您期望的内容,则会导致程序崩溃。 (如果您刚刚启动Java,这很好;您可以再次运行它)

你也可以通过三次询问来轻松分割,例如:

int dob[] = new Integer[3]; // integer array made from Integer class-wrapper
System.out.println("Input day");
dob[0] = Integer.parseInt(input.next()); 
System.out.println("Input month");
dob[1] = Integer.parseInt(input.next());
System.out.println("Input year");
dob[2] = Integer.parseInt(input.next());

现在,您在数组中有三个整数,分割并准备好操作。

如果Integer无法将文本输入解析为数字,则会得到NumberFormatException。

答案 3 :(得分:0)

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.
    }
}