Java: what is wrong in this code?

public static void main(String[] args) {
    // TODO code application logic here
    Scanner input = new Scanner(System.in);
    do{
        System.out.print("Enter choice:");
        int choice;
        choice = input.nextInt();
        switch (choice) 
        {
            case 1: 
                FirstProject.areaRectangle();
                break;
            case 2:
                FirstProject.areaTriangle();
                break;
            default:
                System.out.println("lol");
                break;
        }
    }while (input.nextInt()!=0);    
}




public static void areaRectangle() {
    Scanner input = new Scanner(System.in);
    System.out.println("Area of a rectangle.");

    System.out.print("Enter the width: ");
    double width;
    width = input.nextInt();

    System.out.print("Enter the height: ");
    double height;
    height = input.nextInt();

    double areaRectangle = (width * height);

    System.out.println("The Area of the rectangle is: " + areaRectangle);


    }
public static void areaTriangle() {
    Scanner input = new Scanner(System.in);
    System.out.println("Area of a triangle.");

    System.out.print("Enter the base: ");
    double base;
    base = input.nextInt();

    System.out.print("Enter the height: ");
    double height;
    height = input.nextInt();

    double areaTriangle = (base * height) / 2;

    System.out.println("The Area of the triangle is: " + areaTriangle);
}
}

That is my code and it works, the only thing that is bothering me is that i have to input any value excluding "0" just to keep the loop. Example, if I choose case 1 it will do the method but after doing it, i have to input any value to continue the loop. Any ideas?

Jon Skeet
people
quotationmark

This is the problem:

while (input.nextInt()!=0);

That asks for another number, but doesn't remember it - it just checks whether or not it's 0.

I suspect you want something like:

while (true) {
  System.out.print("Enter choice:");
  int choice = input.nextInt();
  if (choice == 0) {
    break;
  }
  switch (choice) {
    // Code as before
  }
}

There are ways of writing this code which don't require the slightly ugly "infinite until manually broken" loop, but they're slightly odd in other ways. For example:

int choice;
do {
  System.out.print("Enter choice:");
  choice = input.nextInt();
  switch (choice) {
    // Code as before... except work out whether you want to print anything on 0
  }
} while (choice != 0);

Either way, you should really consider what you want to happen when 0 is entered - break immediately, or print "lol" and then break? You can always have:

case 0:
    break;

if you want the switch statement not to print anything for 0.

people

See more on this question at Stackoverflow