sara malik sara malik - 5 months ago 8
Java Question

why when i enter less than 201 its also run the last if statement i don't enter understand

I do not understand the reason why this code is not working proper when I enter less than 200 then last if statement also executed can anyone tell the problem.

This the main problem of this code is not working properly

public class main {
public static void main(String args[]){
Scanner input=new Scanner(System.in);

double unit ;
double extra;
double total_unit;

System.out.println("enter total unit");

unit=input.nextInt();

if(unit >=1 && unit <=200){

unit=unit *8;

System.out.println(" bill of 200 units is "+ unit);

}

if(unit >=201 && unit <=300){

extra = unit - 200;

extra= extra * 10;

total_unit = 200 * 8 + extra;

System.out.println("Total bill is: " + total_unit);

}

if(unit >=301 && unit<=400){

extra=unit-300;

extra=extra *15;

total_unit=200*8 +100*10+ extra;

System.out.println("total bill of more than 300 units is "+total_unit);

}

if(unit >=401 && unit<=500){

extra=unit-400;

extra=extra*20;

total_unit=200*8+ 100*10 + 100*15 + extra ;

System.out.println("total bill between 401 to 500 units" + total_unit);

}

if(unit>501){

extra=unit-500;

System.out.println("unit consumed " + extra + " that above");

extra=extra *25;

System.out.println("------------unit above 500 bill-------- \n" +extra);
total_unit=200*8 + 100*10 +100*15 +100*20 + extra;

System.out.println("---------total bill----------\n " + total_unit);

}

}

}



Answer

I have writen the answer in code why it is executing second condition read the comments in code. if you have any ?s post a comment

 //here your reading the unit value as ex: 190
 unit=input.nextInt(); 

 if (unit >= 1 && unit <= 200) {
        //here your changin the  unit value to 190 * 8 so now unit value is 1520
        unit = unit * 8;
        System.out.println(" bill of 200 units is " + unit);
  }
 //now here your given value is 190 but unit value is changed to 1520    here condition true, that is the reason second condition also excecuting.
 if (unit > 501) {
        extra = unit - 500;
        System.out.println("unit consumed  " + extra + "  that above");
        extra = extra * 25;
        System.out.println("------------unit above 500 bill-------- \n"
                + extra);
        total_unit = 200 * 8 + 100 * 10 + 100 * 15 + 100 * 20 + extra;
        System.out
                .println("---------total bill----------\n  " + total_unit);
    }