The Roman Corner

Personal Projects from art tips to Programming solutions

Case-Switch Explanation

The use of a Case-Switch within the JButton for a Project where you need to create a Rock-Paper-Scissors game-board by extending JFrame. Case-Switch logic is basically a statement where a variable can have any number of outcomes and for those outcomes, a block of code runs. In each scenario a message displays, a number is incremented, and the number of wins is displayed. I had a bit of trouble as I didn't have the breaks after the blocks, it is VERY important to have those or your code won't work!

Case Switch Versus If-Else

Case-Switch statements are quite useful when one or a few variables are the determination of whether a block needs to be executed. In my experience If-Else in smaller bits of code are better as putting together a large Case-Switch statement when 1 thing needs to be checked and excuted. If statements themselves are good if multiple things need to be checked in succession. Generally if you have multiple If-Else statements, using a Case-Switch makes it both easier to read and understand what it does!

Case-Switch Logic


            scissorsButton.addActionListener((ActionEvent ae) ->
         {
            npc = rand.nextInt(3);
            player = 1;
            switch (npc){
               case 0:
                  displayTA.append("Rock crushes Scissors! (Computer Wins)  \n");
                  npcWins++;
                  pWin.setText(""+playerWins);
                  cWin.setText(""+npcWins);
                  nWin.setText(""+draws);
                  break;
               case 1:
                  displayTA.append("Scissors cannot defeat Scissors... (Draw)  \n");
                  draws++;
                  pWin.setText(""+playerWins);
                  cWin.setText(""+npcWins);
                  nWin.setText(""+draws);
                  break;
               case 2:
                  displayTA.append("Scissors Shreds Paper! (Player Wins)  \n");
                  playerWins++;
                  pWin.setText(""+playerWins);
                  cWin.setText(""+npcWins);
                  nWin.setText(""+draws);
                  break;
            }
         });
               
The use of a basic Case Switch used in a Rock-Paper-Scissors game JButton