Search code examples
javaidentifier

Switch statements - illegal start of type, identifier expected, and orphaned case?


I'm trying to create a program where a pseudorandom number generator generates a number and then passes it to an object, which then calls different methods in other Java files. I'm getting errors such as"

Illegal start of type and expected at line 11 switch (randNumber) {

and orphaned case at line 12: case 1;

I've tried removing the space between case and 1, case and 2, and case and 3, however, that returns a orphaned default error.

Could anyone suggest what could be wrong? Both the random.drawHouse() and the random.drawSquare() statements call to two other source codes. I've yet to write the SC for random.drawCircle and I really want to fix everything else before that.

import java.util.Random; 
public class RandomFunTester
{ 

  private RandomFunTester random; 

  RandomFunTester random = new RandomFunTester(); 

  int randNumber = random.nextInt(2) + 1; 

  switch (randNumber) {
    case 1: 
      random.drawHouse(); 
      break; 
    case 2: 
      random.drawSquare(); 
      break; 
    case 3: 
      random.drawCircles(); 
      break; 
    default: 
      System.out.println("The random number generated is not between the values of 1 and 3."); 

  }


}

Solution

  • Could anyone suggest what could be wrong?

    You've put a switch statement in the middle of a class declaration. Statements like this must be in methods or constructors. You haven't given much context here, but you might want something like this:

    class ShapeDrawer {
        private RandomFunTester random = new RandomFunTester(); 
    
        void drawRandomShape() {
            int randNumber = random.nextInt(2) + 1; 
    
            switch (randNumber) {
              case 1: 
                random.drawHouse(); 
                break; 
              case 2: 
                random.drawSquare(); 
                break; 
              case 3: 
                random.drawCircles(); 
                break; 
              default: 
                System.out.println("The random number generated is not "
                                   + "between the values of 1 and 3."); 
            }
        }
    }
    

    Note that you'll never draw circles with this code, assuming RandomFunTester.nextInt() is similar to Random.nextInt() - I'd expect random.nextInt(2) to return either 0 or 1.

    Additionally, RandomFunTester seems to have different roles - come up with a random number and drawing shapes. I realize this isn't production code, but it's never too early to think about giving each class a single responsibility.