从Java方法,如何返回从字符串转换的整个int?

时间:2015-03-08 02:25:23

标签: java methods converter

该计划的目的是输入类似于" 9/7/1994"并返回由正斜杠分隔的数字。 所以它应该出现: 9 7 1994

问题是,一旦我输入日期,它只会返回 9 7 1

我已经考虑过循环getYear()方法,但我不知道怎么做或者这是正确的做法。

import java.util.*;

public class Testing 
{

public static void main(String[] args) 
{
    getDate();
    getMonth(args);
    getDay(args);
    getYear(args);
}


public static void getDate() 
{

    System.out.println("Please enter a date: ");
}


public static int getMonth(Object c) 
{
    char ch = getInputChar();

    int month;

    getInputChar();

    String temp = Character.toString(ch);

    month = Integer.parseInt(temp);

    System.out.println(month);

    return month;

}
public static int getDay(Object c) 
{
    char ch = getInputChar();

    int day;

    getInputChar();

    String temp = Character.toString(ch);

    day = Integer.parseInt(temp);

    System.out.println(day);

    return day;
}
public static int getYear(Object c) 
{

    char ch = getInputChar();

    int year;

    getInputChar();

    String temp = Character.toString(ch);

    year = Integer.parseInt(temp);

    System.out.println(year);

    return year;

}

static char getInputChar() 
{
    char c = '\0';
    try
    {
        c = (char) (System.in.read());
    }
    catch (java.io.IOException ioe) {}
    return c;
}


}

4 个答案:

答案 0 :(得分:3)

您可以利用Java的String正则表达式功能。请尝试以下代码来解析并从输入字符串date中提取三个整数日期。

String date = "9/7/1994";
// the following pattern matches dates of the format DD/MM/YYYY
String pattern = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(date);

if (m.find()) {
    String day = m.group(0); // 9
    String month = m.group(1); // 7
    String year = m.group(2); // 1994
}

答案 1 :(得分:0)

import java.util.*;

public class Testing 
{

    public static void main(String[] args) 
    {
        getDate();
        Scanner sc = new Scanner(System.in);
        String date = sc.nextLine();
        String [] numbers = date.split("/");

        getMonth(numbers[0]);
        getDay(numbers[1]);
        getYear(numbers[2]);
    }

    ...
}

这会帮助您获得所需吗?

答案 2 :(得分:0)

整个程序有两行(如果包含输入格式检查,则为5行)解决方案:

System.out.println("Please enter a date: ");
Scanner s = new Scanner(System.in);
String input = s.nextLine();
if (!input.matches("(1[012]|[1-9])/(3[01]|[12][0-9]|[1-9])/\\d{4}"))
    throw new IllegalArgumentException();
System.out.println(input.replace("/", " "));

要生成正确的(String)输出,不需要解析为整数然后转换回String。

答案 3 :(得分:0)

你只能从年份获得一位数,因为你只读了一位数。以下是getYear()的修改版本,它打印所有4位数字。

    public static void getYear(Object c){
    int year_digit=0;
    String temp;

    for(int i=0;i<4;i++){
        char ch = getInputChar();
        temp = Character.toString(ch);
        year_digit = Integer.parseInt(temp);
        System.out.println(year_digit);
    }
    }

我对你的算法有一个建议: 在getMonth和getDay中,您调用getInputChar两次以获取一个char并跳过'/'表示它。你假设月和日只有一位数。那么10/10/1944呢?一种可能的替代算法是从输入流中读取整个字符串,并使用[输入字符串] .split('/')来获取月,日和年的字符串数组。