好吧所以我的程序的目标(此时非常基本)是接受一串单词,例如:(“我给你34,你给我50”),我想要的是填充我的数组每次出现字符串中的数字。所有这些让我回来的是我给代码的最后一个数字我已经检查了整个阵列,而我能回来的是最后一个数字。
public static void main(String[] args) throws IOException {
BufferedReader read= new BufferedReader(new InputStreamReader(System.in));
String phrase;
int count = 0;
int[] numbers = new int[5];
phrase = read.readLine();
for (int i = 0; i < phrase.length()-1; i++){
if (phrase.substring(i).matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")){
numbers[count] = Integer.parseInt(phrase.substring(i));
count++;
System.out.println(numbers[0]);
}
}
}
答案 0 :(得分:1)
有些事情需要指出。
我不知道你为什么在输入上使用substring
方法。
您只打印了numbers[0]
。无论如何,数组都不好,因为你永远不知道输入有多少个数字。
当您对十进制数字进行分组时,您正在使用parseInt
。
Pattern
&amp;建议Matcher
超过String#matches
这是更正后的代码
List<Double> numbers = new ArrayList<>();
Pattern p = Pattern.compile("([-+]?[0-9]+(?:\\.[0-9]+)?)");
String phrase = "I give you 30, you give me 50. What about 42.1211?";
Matcher m = p.matcher(phrase);
while (m.find()) {
numbers.add(Double.parseDouble(m.group()));
}
System.out.println(numbers); // [30.0, 50.0, 42.1211]