Home > Net >  Create a Java Program to find the maximum between two numbers. Using the switch statement
Create a Java Program to find the maximum between two numbers. Using the switch statement

Time:03-23

Can someone explain how the if method works because I don't understand this code? I understand the if statement part but not the z =0, z =1 part because this is not my code.

    int x,y,z = 0;
    
    System.out.println("Input two numbers: ");
    x=sc.nextInt();
    y =sc.nextInt();
    
    if (x>y) {
        z =0;
    }else if (y>x) {
        z =1;
    }
    
    switch(z) {
        case 0: System.out.print(x   " is greater than "   y  ".");
            break;
        case 1: System.out.print(y   " is greater than "   x  ".");
            break;
        default:    System.out.print("Both are equal.");
    }
}

CodePudding user response:

  • z = 1 is the same thing as z = z 1
  • z = 0 is the same thing as z = z 0

so if x > y then z will have the value 0 and if x < y then z will have the value 1

CodePudding user response:

In this code, z is simply a count of the number of times y was larger than x. The z =1; is just an increment - it's a shorthand notation for z = z 1, so all it does is take z and increase its value by 1 (this increment is so common that many languages have included the = shorthand notation for it). The z =0; things is superfluous, it simply leaves z unchanged.

CodePudding user response:

z  = x;

can also be written as:

z = z   x;

Assuming that int z = 3;

z  = 0;

is pointless and will result in z = 3

z  = 1;

will result in z = 4

  •  Tags:  
  • java
  • Related