Switch


#1

hi! can someone explain to me how the output of that code becomes like this?

double[] tal = { 2.8, 3.8, 0.2, 5.1, 4.9, 127.0, 1.9 }; for (double d : tal) {
switch ((int) d) {
case 0:
System.out.print("A");
case 1:
System.out.print("B");
case 2:
break;
case 3:
case 4:
System.out.print("C");
break;
case 5:
default:
System.out.println();
}
}
output:
CAB
C
B


#2

Well think of case's like if statements so if a certain condition is met your code will behave differently, for example here,

They are exactly 2 occurrences of 3 and 4 in your array,

that is why the output contains 2 C's. :slight_smile:


#3

I'm new with programming, can you explain it more pleas? :frowning:


#4

Your list contains one 3 and one 4, and in your switch statement you created a case that if 3 or 4 is found while looping through your double, it should print "C" :slight_smile:


#5

Hey there. Think of a switch statement as a fork in the road coming to a few paths to take. Each path has a requirement before you can enter it.

So, say each path requires that some part of your vehicle is capable of handling some condition.

e.g. String condition = "rocks";

now, a switch statement for this could be as follows:

switch (condition) {
  case "rocks":
    rocksPath();
  case "slopes":
    slopesPath();
  case "water":
    waterPath();
  default:
    normalPath();
}

You see, it is taking in some input and testing that input for certain values. These tests are known as cases.

These can be rewritten as conditions by using the if conditional statement, like so:

if (condition.equalsIgnoreCase("rocks")) {
  rocksPath();
} else if (condition.equalsIgnoreCase("slopes")) {
  slopesPath();
} else if (condition.equalsIgnoreCase("water")) {
  waterPath();
} else {
  normalPath();
}

switch is just another way of comparing values :slight_smile:


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.