2012-11-26 70 views
0

我無法弄清楚如何處理以下問題。計數輸入空格分隔的數字

我有一個輸入給用戶,他們可以輸入由空格分開的各種數字,例如, (20 30 89 ..) 我需要計算輸入了多少個數字(在這種情況下,輸入了3個數字) 我該怎麼做?

我認爲這背後的邏輯是像計數的空間數量,並加1(它的前面沒有空格的初始數字),但我不知道如何通過代碼來做到這一點。 如果在第一個數字之前輸入空格,並且如果它不是加上+ 1到最後一個數字,也檢查是否有雙重空格,三重空格等,並將它們計爲一個空格,這也是很好的做法。最後看最後是否沒有空間(所以不加起來)。

這裏是我到目前爲止(輸入用戶)有:

package temperature; 

import java.util.*; 

/** 
* @author -- 
*/ 
public class Histogram { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 

     // Input for grades 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter temperatures below (separated by spaces e.g. 20 30 89 ..)"); 
     int temperature = input.nextInt(); 
    } 
} 
+0

您可以將號碼添加到一個數組或列表,檢查列表的大小。或者在讀取新的int時只增加一個計數器。 –

回答

0

如果您只計算空格,您最終可能會將任何垃圾數據視爲數字。我會建議讀取所有輸入,直到您達到空格字符。然後嘗試將其轉換爲整數(或雙精度)(如果轉換失敗),對無效輸入執行錯誤處理,否則增加計數器。

一個例子是這樣的:

// Sample input used. 
    String input = "23 54 343 75.6 something 22.34 34 whatever 12"; 
    // Each number will be temporarily stored in this variable. 
    Double numberInput; 
    // Counter used to keep track of the valid number inputs. 
    int counter = 0; 
    // The index directly after the number ends. 
    int endIndex = 0; 
    // Now we simply loop through the string. 
    for (int beginIndex = 0; beginIndex < input.length(); beginIndex = endIndex + 1) { 
     // Get the index of the next space character. 
     endIndex = input.indexOf(" ", beginIndex); 
     // If there are no more spaces, set the endIndex to the end of the string. 
     if (endIndex == -1) { 
      endIndex = input.length(); 
     } 
     // Take out only the current number from the input. 
     String numberString = input.substring(beginIndex, endIndex); 
     try { 
      // If the number can be converted to a Double, increase the counter. 
      numberInput = Double.parseDouble(numberString); 
      counter++; 
     } catch (java.lang.NumberFormatException nfe) { 
      // Some error handling. 
      System.err.println("Invallid input: " + numberString); 
     } 
    } 
    System.out.println("Total valid numbers entered: " + counter); 

輸出:

Invalid input: something 
Total valid numbers entered: 7 
Invalid input: whatever 

編輯:道歉,我有了答案窗口打開,並沒有看到對方回覆。分割功能應該完美:)

3
  • 只要閱讀使用Scanner#nextLine()方法的完整產品線。
  • 拆分在一個或多個spaces讀線 - 使用+量詞爲 是
  • ,然後得到獲得array的長度。

下面是一個例子: -

if (scanner.hasNextLine()) { 
    int totalNumbers = scanner.nextLine().split("[ ]+").length; 
} 
0

您可以通過空間分割,並計算元素的數量:

System.out.println("20".split (" ").length); 
    System.out.println("20 30".split (" ").length); 

這將分別打印1和2。

這是一個fiddle它。

+0

我做了System.out.println(grades.split(「」).length);我得到錯誤說:int不能被解除引用 – Ilja

0

這是我的解決方案。這比使用Split方法的解決方案稍長一點,但它只包含結果中的數值。所以以下輸入:

12 32 234 555 24 sdf 4354 dsf34r34 rfedfg 4353 

的功能將在數組中返回以下值:

12 
32 
234 
555 
24 
4354 
4353 

下面是函數:

private static String[] getWholeNumbers(String input) { 
    ArrayList<String> output = new ArrayList<String>(); 

    Pattern pattern = Pattern.compile("\\b\\d+\\b"); 
    Matcher matcher = pattern.matcher(input); 
    while (matcher.find()) { 
     output.add(matcher.group()); 
    } 
    return output.toArray(new String[output.size()]); 
} 

如果你只需要計數,該功能可以很容易地改變,以做到這一點。

0

如果你可以將輸入作爲字符串,然後從字符串中檢索數字,會更好。

Scanner input=new Scanner(System.in); 
String st=input.nextLine(); 
String[] split=st.split(" "); 
ArrayList<Integer> temp=new ArrayList<>(); 
String regex="^[0-9]+$"; 
    for(int i=0;i<split.length;i++) 
    { 
     if(split[i].matches(regex)) temp.add(Integer.parseInt(split[i])); 
    } 

現在你得到了所有的temparatures作爲ArrayList<Integer>

相關問題