2015-02-05 129 views
1

想象一下,掃描儀通過任何字符串輸入,如「11 22 a b 22」,該方法應該計算所有數字的總和(例如55)。我在這裏編寫了一些東西,但我無法跳過字符串。任何人都可以幫助我嗎?從掃描儀只讀數

System.out.println("Please enter any words and/or numbers: "); 
String kbdInput = kbd.nextLine(); 
Scanner input = new Scanner(kbdInput); 
addNumbers(input); 

public static void addNumbers(Scanner input) { 
    double sum = 0; 
    while (input.hasNextDouble()) { 
     double nextNumber = input.nextDouble(); 
     sum += nextNumber; 
    } 
    System.out.println("The total sum of the numbers from the file is " + sum); 

} 
+0

這與http://stackoverflow.com/questions/2367381/extract-numbers-from-a-string-java非常相似 - 該解決方案可能適合您 – 2015-02-05 21:54:42

回答

7

爲了能夠繞過非數字輸入,你需要讓你的while循環找還是任何標記的數據流,而不僅僅是double秒。

while (input.hasNext()) 

然後裏面,while循環,看是否下一個標記是doublehasNextDouble。如果不是,您仍然需要通過致電next()來使用該令牌。

if (input.hasNextDouble()) 
{ 
    double nextNumber = input.nextDouble(); 
    sum += nextNumber; 
} 
else 
{ 
    input.next(); 
}