【发布时间】:2016-11-21 04:14:50
【问题描述】:
我一直在寻找答案,但我没有找到对我有很大帮助的答案(有人可能知道指向我的地方)。
我想将一个字符串拆分为一个字符串变量和两个整数变量。我想知道是否有任何方法可以使用我发现的字符串拆分方法并通过其他方式将其用于 int 变量?
代码:
import java.util.Scanner;
public class StringInputStream {
public static void main (String [] args) {
Scanner inSS = null;
String userInput = "Jan 12 1992";
inSS = new Scanner(userInput);
String userMonth = "";
int userDate = 0;
int userYear = 0;
// Can modify anything below here
String[] temp = userInput.split(" ", 2); // "1" means stop splitting after one space
userMonth = temp[0];
userDate = temp[1];
userYear = temp[2];
// Can modify anything above here
System.out.println("Month: " + userMonth);
System.out.println("Date: " + userDate);
System.out.println("Year: " + userYear);
return;
}
}
示例输出:
Month: Jan
Date: 12
Year: 1992
【问题讨论】:
-
最简单的方法是要求用户分别输入日、月和年(3 次调用扫描仪)并分别验证每一个。