2013-10-15 30 views
1

我有一個關於我有任務的快速問題。我想製作一種計算器,它將讀取用戶的輸入,使用if-else-loop找出如何處理它,然後打印相應的結果。 因此,如果用戶輸入:4 * 5,我希望程序檢查兩個整數,並用inChar檢查所需計算的類型,然後執行if-else-loop,其餘部分將完成(我知道如何寫這部分),但是我需要一些關於如何編寫掃描器句子的幫助,它可以檢查一行中不同類型的輸入。希望你明白我的意思。如何讓程序在java中接受來自終端的不同輸入類型的一行?

代碼的一部分,我已經有了:

Scanner input = new Scanner(System.in); 
int a,b; 
char c; 
double sum; 

System.out.println("Velkommen til en helt enkel kalkulator!"); 
System.out.println("Vennligst tast inn regnestykket, paa formen: tall, regneart, tall med mellomrom imellom hver input: "); 

    String svar=input.nextLine(); 


if(c='*'){ 
    sum=a*b; 
}else if(c='/'){ 
    sum=a/b; 
}else if(c='+'){ 
    sum=a+b; 
}else if(c='-'){ 
    sum=a-b; 
}else{ 
    System.out.println("Regnearten var ikke forstaaelig. Programmet termineres."); 
} 
+0

秀部分代碼與掃描儀,你有.. –

+0

簡短和精確的問題獲取更多的關注,只是說。 –

回答

1

一行讀你的輸入線,之後解析它使用兩種String.split()Pattern。要讀取行請使用ScannerSystem.in包裹着BufferedReader

0

我愛regular expressions!所以,讓我們用一個:(\d+)\s*([*/+-])\s*(\d+)

拆毀了

\d+ =一個或多個數字

\s* = 「空間」 零次或多次

[*/+-] =一個*/+,或-

圓括號「捕獲」匹配元素s o您可以稍後訪問它們。在Java中,使用Matcher.group(int),像顯示在下面的片段:。

//Do this only once in your program 
Pattern calcPattern = Pattern.compile("(\\d+)\\s*([*/+-])\\s*(\\d+)"); 

//Do this in your loop 
Matcher m = calcPattern.matcher(input.nextLine()); 
if (m.matches()) { 
    a = Integer.parseInt(m.group(1)); //Get the first group (first set of digits) 
    c = m.group(2); //Get the second group (operator) 
    b = Integer.parseInt(m.group(3)); //Get the third group (second set of digits) 
    //do stuff with a, b, and c 
} else { 
    System.out.println("Please enter a valid expression!"); 
} 

正如在技術人員的進步,正則表達式可容易地擴展 - 與替換(\ d +)(\ d +(:\ d +) ?)接受帶小數的數字,例如。玩弄在線正則表達式測試儀在這裏:http://rubular.com/r/8VibLUpxqP

(快速注:在Java代碼中的正則表達式的雙反斜線是必要的,因爲你不能寫在字符串中的一個反斜槓 - http://docs.oracle.com/javase/tutorial/java/data/characters.html

相關問題