String team1=z.nextLine(), team2;
int num1, num2;
num1 = z.Int();
team1 = z.nextLine();
team1 = team1.replaceAll("[0-9]","");
System.out.println(team1 + " " + num1);
我需要扫描内容为“Alpha Beta Gamma 52”的文本文件。字符串“Alpha Beta Gamma”必须放在team1中,52必须放在num1上。当我使用.replaceAll时,它会删除妨碍我得到整数的52。
答案 0 :(得分:0)
正如您所注意到的,一旦从String中删除了值;该值不在String中。这样的事情怎么样呢?
public static void main(String[] args) {
String in = "Alpha Beta Gamma 52";
String[] arr = in.split(" "); // split the string by space.
String end = arr[arr.length - 1]; // get the last "word"
boolean isNumber = true;
for (char c : end.trim().toCharArray()) { // check if every character is a digit.
if (!Character.isDigit(c)) {
isNumber = false; // if not, it's not a number.
}
}
Integer value = null; // the numeric value.
if (isNumber) {
value = Integer.valueOf(end.trim());
}
if (value != null) {
in = in.substring(0, in.length()
- (String.valueOf(value).length() + 1)); // get the length of the
// numeric value (as a String).
}
// Display
if (value != null) {
System.out.printf("in = %s, value = %d", in, value);
} else {
System.out.println(in + " does not end in a number");
}
}
答案 1 :(得分:0)
public static void main(String[] args) {
String readLine = new Scanner(System.in).nextLine();
String team1 = readLine.replaceAll("\\d", "");
int team2 = Integer.parseInt(readLine.replaceAll("\\D", ""));
System.out.println(team1); //Alpha Beta Gamma
System.out.println(team2); //52
}
答案 2 :(得分:0)
在数字前拆分,然后解析部分:
String[] parts = str.split(" (?=\\d)");
String team = parts[0];
int score = Integer.parseInt(parts[1]);