2014-03-12 84 views
-1

我覺得自己像一個白癡不能弄清楚這一點。有人可以幫助我把它變成切換語句嗎?如何更改if/else語句來切換語句

if (nextInput.equals("*")) 
    f = new Fraction(f.times(f1)); 
else if (nextInput.equals("+")) 
    f = new Fraction(f.times(f1)); 
else 
    f = new Fraction(f.minus(f1)); 
+1

[你在這裏](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html) – Baby

+0

從Java 7,您可以使用馬桶蓋statment字符串。對於語法讀取oracle文檔... – Stunner

+0

可能的重複[Switch with Strings in Java](http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java) – SudoRahul

回答

4
String text = ""; 

switch(text) 
{ 
case "*": 
    f = new Fraction(f.times(f1)); 
    break; 
case "+": 
    f = new Fraction(f.times(f1)); 
    break; 
default : 
    f = new Fraction(f.minus(f1)); 
} 

Switch接受JDK 7字符串或更高

1

像這樣的事情,你需要

String x="";   
switch(x)  
{   
case "*":f = new Fraction(f.times(f1));break;   
case "+":f = new Fraction(f.times(f1));break;   
default:f = new Fraction(f.minus(f1));    
} 

注意:開關字符串將只在JDK7工作,或更高版本

0

您應該閱讀文件塔季翁。試試這個:

switch(nextInput){ 
    case "*": 
     f = new Fraction(f.times(f1)); 
     break; 
    case "+": 
     f = new Fraction(f.times(f1)); 
     break; 
    default: 
     f = new Fraction(f.times(f1)); 
}