java - 从一行字符串中删除一个整数。然后,将 int 放入变量

标签 java string int java.util.scanner

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。

最佳答案

正如您所注意到的,一旦您从字符串中删除值;该值不在字符串中。改用这样的东西怎么样?

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");
  }
}

关于java - 从一行字符串中删除一个整数。然后,将 int 放入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20592267/

相关文章:

java - 在 WSL 上运行 Kafka 并在 Windows 上创建生产者

python - 如何解析/格式化一串元组?

c - 用 C 语言中另一个字符串中的字符替换字符串字符

.net - 如何使 IEnumerable<string>.Contains 不区分大小写?

c - 使用 uint8_t 数据的 int 类型矩阵在传递给函数时打印错误

c - while 循环中的 scanf() 没有终止?

java - 谁决定 Java 中数据类型的大小

java - 单击新 Activity 内的微调器时强制关闭。

java - 霍夫曼编码算法给出奇怪的树(Java)

c++ - 使用 int 而不是 size_t 索引来访问 vector 元素会降低性能吗?