I am trying to illustrate the use of the switch() statement using a prompt box.

//Program to show day of week using switch() statement
    //Problem - prompt box not working first time but works after that.
    function setup()
    {

        createCanvas(800,800);


    }
    function draw()
    {

        background(255);


        mySwitch();

    }



    function mySwitch()
    {
        var num1 = prompt("Enter days of week 0-6");

        var num1a=int(num1);




        switch (num1a) {
            case 0:{
                text("Sunday", 50, 50);

                    }
            break;
        case 1:
                {

            text("Monday", 60, 60);
                }
            break;
        case 2:
            {
            text("Tuesday", 70, 70);
             }
            break;
        case 3:
            {
            text("Wednesday", 90, 90);
            }
            break;

        case 4:
            {
            text("Thursday", 110, 110);
            }
            break;
        case 5:
            {
            text("Friday", 140, 140);
            }
            break;
        case 6:
            {
            text("Saturday", 170, 170);
            }
            break;
        default:
            {
                text("Invalid entry 0 ->6 only!!", 200,200);
            }
            break;
    }

    }//end function
Tagged:

Answers

  • The {} inside case are not necessary

  • using prompt() in a loop like draw() is evil :((

    It may also be contributing to your problem... Instead try using noLoop():

    function setup() {
      createCanvas(800,800);
      noLoop();
      mySwitch();
    }
    
    function mySwitch() {
      var num1 = prompt("Enter days of week 0-6");
      var num1a=int(num1);
    
      switch (num1a) {
        case 0:
          text("Sunday", 50, 50);
        break;
        case 1:
          text("Monday", 60, 60);
        break;
        case 2:
          text("Tuesday", 70, 70);
        break;
        case 3:
          text("Wednesday", 90, 90);
        break;
        case 4:
          text("Thursday", 110, 110);
        break;
        case 5:
          text("Friday", 140, 140);
        break;
        case 6:
          text("Saturday", 170, 170);
        break;
        default:
          text("Invalid entry 0 ->6 only!!", 200,200);
        break;
      }
    
    }//end function
    

    If you want the prompt to reappear after each input you can simply call mySwitch() at the end of mySwitch() (recursion!); BUT, whatever you do you, MUST add a condition that will break the loop - e.g. if user submits no value - otherwise you lock up the browser which is very unfriendly to users...

    Also from a user experience perspective it would make more sense to accept input of 1 to 7. You can always minus 1 if you need to use the number to reference an element in an array later.

Sign In or Register to comment.