2014-01-12 32 views
3

我有代碼需要輸入,然後計算出你想要用它做什麼Java - 解析簡單計算器程序的字符串的問題

例如。你會輸入「x(+, - ,.. etc)y」,它會爲你計算它。

即時通訊目前使用掃描儀和分裂它使得

double x = input.nextDouble(); 
String z = input.next(); 
double y = input.nextDouble(); 

現在我遇到了一個問題。說我想做一個階乘,我會輸入「x!」但代碼仍然需要最後一次input.nextDouble();

我該怎麼去(使用我在做的事情,如果可能的話)檢查是否所有3都有輸入,然後在使用if語句的方法之間進行選擇,或者只有2個輸入。

相對碼

System.out.print("> "); 
double x = input.nextInt(); 
String z = input.next(); 
double y = input.nextInt(); 

if (x == 0) { 
running = false; 

} else if (z.equalsIgnoreCase("+")) { 

    System.out.println(addition(x, y)); 

} 
+0

您可以檢查運算符是一元運算符還是二元運算符。如果操作員對單個操作數進行操作,則需要單個輸入。如果操作員是二進制的,則需要兩個輸入。你將不得不檢查操作員哪個用戶想要做什麼..然後採取輸入。希望它可以幫助你。 – Coder

+0

爲什麼0不是有效的第一個參數? – kukido

回答

4

相反獲得三個不同的輸入,只是輸入串的一行的,因此分析該字符串,並輸入它們轉換成所需類型。通過這種方式,您可以從字符串中確定一個因子(1個變量)或其他任何操作。

使用掃描儀。

  boolean binary = true; 
    Scanner input = new Scanner(System.in); 
    double x = input.nextInt(); 
    String z = input.next(); 
    //check if z is a unary operator ie. 
      if(z=='!') 
       binary = true; 
    if(binary) 
     double y = input.nextInt(); 
+0

它比Scanner更好嗎? – kukido

+0

問題不在於使用掃描儀,您可以使用任何閱讀器。 OP所面臨的問題是他需要一個解決方案來操作Unary和Binary操作員。所提供的解決方案不是特定的或僅限於掃描儀。 – xvidun

+0

我同意你的看法,但是OP也提到「(使用我在做的事情,如果可能的話)」。 – kukido

2

如果您有兩個輸入,那麼您的代碼將拋出NoSuchElementException。爲了避免這種情況,您應該使用input.hasNext()

double x = input.nextInt(); 
String z = input.next(); 

if (input.hasNext()) { 
    // input has y 
    y = input.nextInt(); 
    // perform operation on two elements 
} else { 
    // no y 
    // perform operation on one element 
} 
0

添加一個額外的if語句,並且僅當z ='+'時纔要求'y'。

System.out.print("> "); 
double x = input.nextInt(); 
String z = input.next(); 


if (x == 0) { 
running = false; 

} else if(z.equalsIgnoreCase("!")){ 
    factorial(x); 
} 
else if (z.equalsIgnoreCase("+")) { 
double y = input.nextInt(); 
System.out.println(addition(x, y)); 

}

0

試試這個代碼

double y = 0.0; 
    if(!z.contains("!")){ 
    y = sc.nextDouble(); 
    } 
0

你必須得到輸入的字符串,所以你必須使用String.indexof()和劃分主串兩個字符串必須parse像第一部分這個:

int a=Integer.parse(someString); 

和你的鋼琴的第二部分克會告訴你你必須做什麼。