-1

I am trying to understand how loops work but I can't seem to piece it together. I am working on a shipping java program and whatever I try will not work. So far I have when the integers are correct it proceeds with the program, but I want it when I put in an invalid number (such as zero or a negative) to ask again.

    Scanner input = new Scanner (System.in);

    int weight;
    int distance;
    int rate;

    System.out.println("Welcome to the You Send It We Rend It Shipping Company!"); {
        System.out.println ("How heavy is your package in pounds?");
        weight = input.nextInt();
    }

    while (weight <=1 || weight >=60);{
        System.out.println ("How far will you be shipping the package in miles?");
    distance = input.nextInt();
    }
    while (distance <1);

        double x = 0.00;
        if (weight >= 1) x=5.01;
        if (weight >=11) x=7.02;
        if (weight >=21) x=9.03;
        if (weight >=31) x=11.04;
        if (weight >=41) x=15.00;

        rate = (distance+99)/100;

        System.out.printf ("Your total shipping cost for %d miles is $%s\n",distance, rate*x);


}

Also, I would like to fully understand why the rate is that way...?

rate = (distance+99)/100;
Xela
  • 3
  • 2
  • You should recheck what `{}` mean and what they do. For example this `System.out.println("Welcome to the You Send It We Rend It Shipping Company!"); { ... }` doesn't do what you may think it does. – Tom Nov 09 '15 at 04:23

2 Answers2

1

You could introduce a boolean.. We will continue to loop as long as our boolean is set to false. If we satify a condition, we set the boolean to true, and leave the loop.

boolean validWeight = false;
while(!validWeight)
{
     System.out.println ("How heavy is your package in pounds?");
     weight = input.nextInt();
     if(weight > 1 && weight <60)
          validWeight = true;
}

Also, careful with this line:

while (distance <1);

which is equivalent to

while(distance < 1)
{
     //do nothing
}

if distance is set to anything less than one, you will be in an infinite loop.

Same problem with

 while (weight <=1 || weight >=60);

Putting a ";" right after a conditional statement is the same as putting

{
     //do nothing
}

Which will only cause you a lot of problems

telefunken
  • 138
  • 7
0

For example, if you want user to enter a valid weight, you can use the following loop:

    int weight = 0;
    Scanner input = new Scanner(System.in);
    do {
        System.out.println("How heavy is your package in pounds?");
        weight = input.nextInt();
        if (weight <= 0) {
            System.out.println("Weight should be a positive integer, please enter again!");
        }
    } while (weight <= 0);
Bon
  • 3,073
  • 5
  • 21
  • 40