我一直在寻找一个答案,但我没有找到一个可以帮助我的人(有人可能知道在哪里指向我)。Java:将字符串拆分为单独的字符串和整数变量
我想将一个字符串分成一个字符串变量和两个整数变量。我想知道是否有用户使用我发现的字符串拆分方法,并通过其他方式将它用于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
看到https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String) –
最简单的方法将是问用户分别输入日,月和年(3次调用扫描器)并分别验证每一个。 – alfasin