Log in

View Full Version : how to convert from If/If Else to Switch Statement



atom715
10-28-2015, 03:32 AM
I need to convert the if statement inside my program to a switch statement for a school assignment and I have no clue where to start or how to change it. Please help me! sorry if I did this incorrectly I have never posted here before.



import java.util.Scanner;

public class hw_question_2{

public static void main(String[] args){

Scanner input=new Scanner(System.in);
double x, y;

System.out.println("The value for 'x' can be 7, 15, or 30");
System.out.println("Enter a value for 'x'");
x=input.nextDouble();

System.out.println("Enter a value for 'y'");
y=input.nextDouble();

if (x==7)
y=7.5;
else if (x==15)
y=8.50;
else if(x==30)
y=9.0;
else y=10.0;

System.out.print("The value for 'x' is: " +x +"\n");
System.out.print("The value for 'y' is: " +y +"\n");

}
}

Beverleyh
10-28-2015, 08:04 AM
If this is for your school assignment, you should probably seek help from your classmates or tutor/teacher.

styxlawyer
10-28-2015, 03:38 PM
As this appears to be a Java course that you're studying this page (http://www.homeandlearn.co.uk/java/java_switch_statements.html) might help.

Incidentally, the "switch" statement syntax is common to C, C++, Java, JavaScript and PHP; so it's a good thing to learn.