javadebuggingreview

How can I fix this do\while and switch\case loop. The outputs of the methods in the switch case Test Satisfactorily


Assuming these Methods work, which I had tested earlier, can I ask for a second set of eyes on what I'm doing wrong in this While loop? I am looking for it to repeat for shapes until the user inputs a 0 specifically. as the text shows im doing Circle, Triangle and Rectangle.

public static void main(String[] args) 
{
       
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter an integer representing the shape would you         like the area of.n/ (1-Triangle, 2-Circle, 3-Rectangle)");
          int shape = scanner.nextInt();
            do{
               //dowhile loop
                 int shapecheck=1;
                 switch(shape)
                        {
                        case 1:CalcArea.CalcTri();
                        System.out.println("Another shape? (1-yes, 0-no)");
                        int shapecheck = scanner.nextInt();
                        break;
            
                        case 2:CalcArea.CalcCir();
                        System.out.println("Another shape? (1-yes, 0-no)");
                        int shapecheck = scanner.nextInt();
                        break;
            
                        case 3:CalcArea.CalcRect();
                        System.out.println("Another shape? (1-yes, 0-no)");
                        int shapecheck = scanner.nextInt();
                        break;
            
                        default:
                        shapecheck = 0;
                        }    
            }while (shapecheck==1);  
}

Solution

  • Move the declaration of shapecheck outside the loop so it is visible in the loop condition. Don't redeclare the variable inside the cases; assign to it instead.

    int shapecheck = 1;
    do {
        switch (shape) {
            case 1:
                CalcArea.CalcTri();
                System.out.println("Another shape? (1-yes, 0-no)");
                shapecheck = scanner.nextInt();
                break;
            case 2:
                CalcArea.CalcCir();
                System.out.println("Another shape? (1-yes, 0-no)");
                shapecheck = scanner.nextInt();
                break;
            case 3:
                CalcArea.CalcRect();
                System.out.println("Another shape? (1-yes, 0-no)");
                shapecheck = scanner.nextInt();
                break;
            default:
                shapecheck = 0;
        }
    } while (shapecheck == 1);