好吧,我的程序的目标(此时非常基本)是接受一串单词,例如:(“我给你 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]);
}
}
}
最佳答案
有些事情需要指出。
我不知道您为什么在输入上使用
substring
方法。您只打印了
数字[0]
。无论如何,数组都不好,因为你永远不知道输入将有多少个数字。当您对十进制数进行分组时,您正在使用
parseInt
。
更受推荐Pattern
和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]
关于java - 无法让我的程序接受多个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42259561/