【问题标题】:Splitting a string into different array indexes Java?将字符串拆分为不同的数组索引Java?
【发布时间】:2013-01-31 01:55:38
【问题描述】:

我正在尝试将字符串拆分为不同的数组索引。该字符串来自用户输入(通过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");
    }
}

【问题讨论】:

    标签: java arrays string java.util.scanner


    【解决方案1】:
    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() 获取今天的准确日期,并与之进行比较。

    【讨论】:

      【解决方案2】:

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

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

      这使用Joda Time library

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

      【讨论】:

        【解决方案3】:

        我注意到您正在使用键盘输入来识别字符串。如果用户没有输入您期望的内容,它将使您的程序崩溃。 (如果你刚刚启动 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。

        【讨论】:

          【解决方案4】:
          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.
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-11-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-03
            • 2016-04-01
            相关资源
            最近更新 更多