-1

I feel like an idiot not being able to figure this out. Can someone please assist me in making this into a switch statement?

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
    [here you are](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html) – Baby Mar 12 '14 at 06:56
  • From java 7, you can use strings in swtich statment.For syntax read oracle documentation... – Stunner Mar 12 '14 at 06:56
  • possible duplicate of [Switch Statement with Strings in Java](http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java) – Rahul Mar 12 '14 at 06:56
  • switch (nextInput) { case "*": break; case "+": break; } etc... – takendarkk Mar 12 '14 at 06:56

3 Answers3

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 accept String in jdk 7 or higher

Kick
  • 4,823
  • 3
  • 22
  • 29
1

Something like this you need

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));            
}

Note: switch Strings will only work in jdk7 and or higher versions

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

You should read the documentation. Try this:

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));
}