2017-02-15 29 views
0

沒問題,所以我的程序(在這一點上非常基本)的目標是採取一串字,例如:(「我給你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

應該不是你的正則表達式只是 「[0-9] +」 –

+0

你爲什麼捕捉浮動數字並使用'parseInt'? –

+1

可能不相關。 'System.out.println(numbers [count]);'count ++之前? –

回答

1

有些事情需要指出。

  • 我不知道你爲什麼在輸入上使用substring方法。

  • 您只打印numbers[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] 
相關問題