PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label switch-statement. Show all posts
Showing posts with label switch-statement. Show all posts

Sunday, December 18, 2022

[FIXED] Why is chaining labels in the switch syntax allowed and what does it do?

 December 18, 2022     java, switch-statement, syntax     No comments   

Issue

I recently discovered, that in a java switch statement, multiple labels can be chained, but for no apparent effect. And it even allows labels that do not exist. For example you can do this: case ENUM_VALUE_1:ENUM_VALUE_2:, or even this case ENUM_VALUE_1:foobar:barfoo:. As long as it ends with a colon, any value seems to be accepted. First I though this might be a different way of grouping multiple cases, but that does not seem to be working. So I ran the following test

public class Main {

public enum TestEnum {
    A,
    B
}

public static void main(String[] args) {
    TestEnum testEnum = TestEnum.B;

    switch (testEnum) {
        case A: System.out.println("Test 1: Case 1"); break;
        case B: System.out.println("Test 1: Case 2"); break;
    }

    switch (testEnum) {
        case A: System.out.println("Test 2: Case 1"); break;
        case B:A: System.out.println("Test 2: Case 2"); break; // Label A is already used in enum
    }

    switch (testEnum) {
        case A:B: System.out.println("Test 3: Case 1"); break; // Label B is already used in enum
        case B: System.out.println("Test 3: Case 2"); break;
    }

    switch (testEnum) {
        case A:BARFOO: System.out.println("Test 4: Case 1"); break; // Label BARFOO does not exist
        case B:FOOBAR: System.out.println("Test 4: Case 2"); break; // Label FOOBAR does not exist
    }

    switch (testEnum) {
        case A:B: System.out.println("Test 5: Case 1"); break;
    }
}}

I ran it in java 11 and 17 and the output in both versions is:

Test 1: Case 2
Test 2: Case 2
Test 3: Case 2
Test 4: Case 2

I would have expected that only test 1 and 5 actually compile, but they all compile and it seems that everything after the actual label is just ignored.

I doubt this is an oversight, so what am I missing?


Solution

Where in your code you have something like this:

case A:BARFOO:

BARFOO: isn't a switch case. It's nothing to do with the switch mechanics. It's just a label. You're allowed to label any statement, but it's not always useful. It's typically used for loops: e.g.

outerloop:
while (true) {
    while (true) {
        break outerloop;
    }
}

If you actually wanted to group together multiple cases, you could write it like:

case A: case B:
    ...
    break;

And as Jesper mentions in the comments, more recent versions of Java also support a switch expression, under which the syntax is:

case A, B -> ...


Answered By - khelwood
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, December 17, 2022

[FIXED] How to assign a new value in switch case which in a function?

 December 17, 2022     javascript, switch-statement, syntax     No comments   

Issue

Currently writing a function that converts a numerical grade into American system. Basically the result should be like this:

You got a D (60%)!

But I get this :

You got a 60 60%!

Apart from the brackets what should I do to make it look like as much as possible?

the code is below:

function gradeConverting(grade) {
    let gradePercent = grade + "%";
    switch (grade) {
        case (90 < grade && grade <= 100):
            grade = "A";
            break;
        case (80 < grade && grade <= 89):
            grade = "B";
            break;
        case (70 < grade && grade <= 79):
            grade = "C";
            break;
        case (60 <= grade && grade <= 69):
            grade = "D";
            break;
        case (50 <= grade && grade <= 59):
            grade = "E";
            break;
        case (grade <= 49):
            grade = "F";
            break;
    }
    return console.log("You got a " + grade + " " + gradePercent + "!");
}

gradeConverting(55);

Solution

The logic of your code is completely valid but you are using switch() in a wrong way.

check the doc about : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

if you put switch(grade) then something in case something is expect a value that match grade instead of an expression that return true|false

For example:

switch (grade) {
        case 90: // only for grade === 90
            grade = "A";
            break;
        case 55: // only for grade === 55
        ...

Indeed you can have a function with multiple ifstatement then return lettergrade. Or still use the current logic with some modification and still utilize switch().

I create another variable for lettergrade, recommend don't modify grade unless you know what you are trying to do.

function gradeConverting(grade) {
    let gradePercent = grade + "%";
    var lettergrade = ""; 
    switch (true) { // change to true 
        case (90 <= grade && grade <= 100):
        // you want (90 <= grade && grade <= 100) to be evaluated as true in order to execuate
            lettergrade = "A";
            break;
        case (80 <= grade && grade <= 89):
            lettergrade = "B";
            break;
        case (70 <= grade && grade <= 79):
            lettergrade = "C";
            break;
        case (60 <= grade && grade <= 69):
            lettergrade = "D";
            break;
        case (50 <= grade && grade <= 59):
            lettergrade = "E";
            break;
        case (grade <= 49):
            lettergrade = "F";
            break;
    }
    return console.log("You got a " + lettergrade + " (" + gradePercent + ")!");
}

gradeConverting(100);



Answered By - Yunhai
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, November 14, 2022

[FIXED] How to pattern match for a True/False within a function in Haskell?

 November 14, 2022     error-handling, functional-programming, haskell, if-statement, switch-statement     No comments   

Issue

I am trying to handle file errors manually so I can print my own message and currently I have this code:

handleFileError :: FileError -> IO a
handleFileError (FileError errorKind) = do
  case errorKind of
    NotFound -> undefined
    NoPermission -> undefined
    IsDirectory -> undefined

fileRead :: String -> IO String
fileRead file = do
  pathExists <- doesPathExist file
  notDirectory <- doesFileExist file

  -- These two must be handled before `System.Directory.getPermissions` is called
  -- or else it will error.

  permissions <- getPermissions file
  let hasReadPermissions = readable permissions

  if hasReadPermissions then undefined -- This is the success case
  else handleFileError $ FileError NoPermissions

I would like to check if any of the 3 booleans (pathExists, notDirectory, and hasReadPermissions) are false, and then act accordingly. I tried to implement this using a case with False, however this just always runs the first branch.


Solution

One way would be to use MultiWayIf:

do
  pathExists <- doesPathExist file
  notDirectory <- doesFileExist file
  permissions <- unsafeInterleaveIO (getPermissions file)
  if
    | not pathExists -> -- ...
    | not notDirectory -> -- ...
    | not permissions -> -- ...
    | otherwise -> -- ...

If you're allergic to extensions, the old-fashioned way to get this feature is using guards, as in:

  case () of
    _ | not pathExists -> -- ...
      | not notDirectory -> -- ...
      | not permissions -> -- ...
      | otherwise -> -- ...

But I recommend neither of these. Instead, just do something with the file, and catch the exception; otherwise there are race conditions with the file system changing out from under you between the check and the file use. Like this:

fileRead :: String -> IO String
fileRead = catch (undefined {- success case -}) $ \e -> if
  | isDoesNotExistError e -> -- ...
  | isPermissionError e -> -- ...
  | otherwise -> throw e


Answered By - Daniel Wagner
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, November 7, 2022

[FIXED] How to make a Java Main Menu Loop after using a case

 November 07, 2022     java, loops, menu, switch-statement     No comments   

Issue

I am pretty dang new to Java, but being familiar with some other programming languages, I know the basic lay out of a lot of it. One thing I am struggling with is looping menus, specifically a main menu.

I have tirelessly researched methods of it, but none seem to apply or work to my program. I'm assuming its something silly and small that I'm missing in my more-so basic program.

Check it below, thanks for any tips.

    import java.util.Scanner;
public class basicCalc {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);
        boolean mainLoop = true;

        int choice;
        do{
            System.out.println("Calculator Main Menu\n");
            System.out.print("1.) Addition \n");
            System.out.print("2.) Subtraction.\n");
            System.out.print("3.) Multiplication.\n");
            System.out.print("4.) Division.\n");
            System.out.print("5.) Generate Random Number.\n");
            System.out.print("6.) Exit\n");
            System.out.print("\nEnter Your Menu Choice: ");

            choice = input.nextInt();


        }

        while(choice >7);

        switch(choice){

        case 1:
            //Definitions
            int adNumf, adNuml, sum;
            System.out.print("Please Enter The First Number: ");
            adNumf = input.nextInt();
            System.out.print("\nPlease Enter The Second Number: ");
            adNuml = input.nextInt();
            sum = adNumf + adNuml;
            System.out.print("The Sum Of Those Numbers is: " +sum);
            break;

        case 2: 
            int subNum1, subNum2, sum2;
            System.out.println("\nPlease Enter The First Number: ");
            subNum1 = input.nextInt();
            System.out.println("Please Enter The Second Number: ");
            subNum2 = input.nextInt();
            sum2 = subNum1 - subNum2;
            System.out.println("The Subtraction Leaves The Number: " +sum2);
            break;

        case 3:
            int multNum1, multNum2, multTotal;

            // Gather Input
            System.out.println("Please Enter The First Number To Multiply: ");
            multNum1 = input.nextInt();
            System.out.println("Please Enter The Second Number To Multiply: ");
            multNum2 = input.nextInt();

            // This will Multiply the Numbers
            multTotal = multNum1 * multNum2;

            //Display Final
            System.out.println("The Multiplied Numbers Are: " +multTotal);
            break;

        case 4: 
            //Definitions
            double divNum1, divNum2, divTotal;
            System.out.println("Enter Your Numerator ");
            divNum1 = input.nextInt();
            System.out.println("Enter Your Denominator ");
            divNum2 = input.nextInt();
            if(divNum2 == 0){
                System.out.println("Zero is Not divisable, please select a new denominator: ");
                divNum2 = input.nextInt();
            }
            divTotal = divNum1 / divNum2;
            System.out.println("Your divisor is: " +divTotal);
            break;

        case 5:
            double limL, limH, rand;
            System.out.println("Enter Your Low Limit: ");
            limL = input.nextInt();
            System.out.println("Enter Your High Limit ");
            limH = input.nextInt();

            //Equation to keep numbers within bounds
            rand = limL + (Math.random() * ((limH - limL) + 1));
            System.out.println("Given Your Limits, the Random Number will be: " +rand);
            break;

        case 6: 
            System.out.println("Exiting Program...");
            System.exit(0);
             break;
        }



        // Bad Menu Option Direct
    if (choice > 6 || choice < 1){
        System.out.println("This is not a valid Menu Option! Please Select Another.");
        do{
            choice = input.nextInt();
        }
        while(choice < 7 );
    }
    // End bad menu option  


    }

}

Solution

You can give whole code(from displaying menu) inside a while loop and give condition as true so that after using a case it will automatically repeat(as you are using 6 to EXIT). And if any invalid input is given for eg:10 the case will go to default section and will execute the code there

import java.util.Scanner;
public class basicCalc {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner input = new Scanner(System.in);
    boolean mainLoop = true;

    int choice;
    while(true){
        System.out.println("Calculator Main Menu\n");
        System.out.print("1.) Addition \n");
        System.out.print("2.) Subtraction.\n");
        System.out.print("3.) Multiplication.\n");
        System.out.print("4.) Division.\n");
        System.out.print("5.) Generate Random Number.\n");
        System.out.print("6.) Exit\n");
        System.out.print("\nEnter Your Menu Choice: ");

        choice = input.nextInt();




    switch(choice){

    case 1:
        //Definitions
        int adNumf, adNuml, sum;
        System.out.print("Please Enter The First Number: ");
        adNumf = input.nextInt();
        System.out.print("\nPlease Enter The Second Number: ");
        adNuml = input.nextInt();
        sum = adNumf + adNuml;
        System.out.print("The Sum Of Those Numbers is: " +sum);
        break;

    case 2: 
        int subNum1, subNum2, sum2;
        System.out.println("\nPlease Enter The First Number: ");
        subNum1 = input.nextInt();
        System.out.println("Please Enter The Second Number: ");
        subNum2 = input.nextInt();
        sum2 = subNum1 - subNum2;
        System.out.println("The Subtraction Leaves The Number: " +sum2);
        break;

    case 3:
        int multNum1, multNum2, multTotal;

        // Gather Input
        System.out.println("Please Enter The First Number To Multiply: ");
        multNum1 = input.nextInt();
        System.out.println("Please Enter The Second Number To Multiply: ");
        multNum2 = input.nextInt();

        // This will Multiply the Numbers
        multTotal = multNum1 * multNum2;

        //Display Final
        System.out.println("The Multiplied Numbers Are: " +multTotal);
        break;

    case 4: 
        //Definitions
        double divNum1, divNum2, divTotal;
        System.out.println("Enter Your Numerator ");
        divNum1 = input.nextInt();
        System.out.println("Enter Your Denominator ");
        divNum2 = input.nextInt();
        if(divNum2 == 0){
            System.out.println("Zero is Not divisable, please select a new denominator: ");
            divNum2 = input.nextInt();
        }
        divTotal = divNum1 / divNum2;
        System.out.println("Your divisor is: " +divTotal);
        break;

    case 5:
        double limL, limH, rand;
        System.out.println("Enter Your Low Limit: ");
        limL = input.nextInt();
        System.out.println("Enter Your High Limit ");
        limH = input.nextInt();

        //Equation to keep numbers within bounds
        rand = limL + (Math.random() * ((limH - limL) + 1));
        System.out.println("Given Your Limits, the Random Number will be: " +rand);
        break;

    case 6: 
        System.out.println("Exiting Program...");
        System.exit(0);
         break;
    default :
             System.out.println("This is not a valid Menu Option! Please Select Another");
             break;

    }


    }




    }

   }


Answered By - Anoop LL
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I combine the menu items inside the swicth case in C#

 November 07, 2022     .net-framework-version, c#, menu, switch-statement, winforms     No comments   

Issue

  • I have several menu items under the View menu in my parent form, each one of these menu items opens a child form.
  • I can call the child forms with a separate method for each menu item, but I want to combine all the menu items inside a switch case.
  • How do I do that?

Menu Image

Separate event method for each child:

private void child1ToolStripMenuItem_Click(object sender, EventArgs e)
{
  if(Application.OpenForms["Child1"] is Child1 ch1)
  {
    ch1.Focus();
    return;
  }
  ch1= new Child1();
  ch1.Name = name1; //name assigned in parent form
  ch1.Age = age1; // age assigned in parent form;
}

I have written the following code to combine the menu inside the switch statement, it isn't showing any error but does not display the child form either.

private void viewToolStripMenuItem_Click(object sender, EventArgs e)
{
  ToolStripMenuItem menu = sender as ToolStripMenuItem;
            
   switch(menu.Name)
            {
                case "Child1":
                    if(Application.OpenForms["Child1"] is Child1 ch1)
                    {
                        ch1.Focus();
                        return;
                    }
                    ch1= new Child1();
                    ch1.Name = name1; //name assigned in parent form
                    ch1.Age = age1; // age assigned in parent form;
                    ch1.show();
                    break;
                case "Child2":
                    if (Application.OpenForms["Child2"] is Child2 ch2)
                    {
                        ch2.Focus();
                        return;
                    }
                    ch2 = new Child2();
                    ch2.Name = name2; //name2 assigned in parent form
                    ch2.Age = age2; // age2 assigned in parent form;
                    ch2.show();
                    break;

                case "Child3":
                    if (Application.OpenForms["Child3"] is Child3 ch3)
                    {
                        ch3.Focus();
                        return;
                    }
                    ch3 = new Child3();
                    ch3.Name = name3; //name3 assigned in parent form
                    ch3.Age = age3; // age3 assigned in parent form
                    ch3.show();
                    break;
                default:
                    break;

            }
}

Solution

okay I solved it, if anyone is looking for the same problem, the solution is in the Parent.Designer.cs window where you find auto-generated code for the controls.

this.chil1ToolStripMenuItem.Name = "chil1ToolStripMenuItem"

so the menu.name in Parent.cs should be the same as the one above name or you can edit the this.chil1ToolStripMenuItem.Name = "chil1ToolStripMenuItem" to

this.chil1ToolStripMenuItem.Name = "chil1Menu"



Answered By - Lha
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, October 25, 2022

[FIXED] What is wrong with my recursive back-tracker

 October 25, 2022     algorithm, java, maze, oop, switch-statement     No comments   

Issue

I wanted to make an algorithm to create a maze using recursive back-tracker algorithm. I get this problem when running the program:

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Vector.firstElement(Vector.java:481)
    at DC_files.Maze.RBT(MazeAlgorithm.java:131)
    at DC_files.MazeAlgorithm.main(MazeAlgorithm.java:222)

and honestly, at this point after finding couple of bugs and error i have no idea what might be wrong. The only clue that i have, is that in the switch there is an error, that the stack.firstElement() doesn't update and is always the same and in the cases something is being inserted wrongly.

while(vis < toVis){
    Vector<Integer> neighbours = new Vector<>();
    int x = stack.firstElement().getKey();   (line 131 with the error.)
    int y = stack.firstElement().getValue();


            //North neighbour
            if(y-1 >= 0 && !matrix[y - 1][x].vis){
                neighbours.add(0);
            }

entire code

package DC_files;
import javafx.util.Pair;
import java.util.Random;
import java.io.*;
import java.util.*;

class Cell{

    /*
      each Cell holds information of:
        -the state of it's walls,
        -the value that the Cell holds(will be used later to customize rooms in the maze),
        -and information if the Cell was visited(will be used in the algorithm)
     */


    boolean[] walls;
    boolean vis;
    int value;


    public boolean isVis() {
        return vis;
    }

    public boolean[] getWalls() {
        return walls;
    }

    public int getValue() {
        return value;
    }


    /*
        by default, each Cell has the value of each wall set to true(they exist/there are no corridors),
        vis as visited set to false, because we weren't in the room yet,
        value set to zero, for further development phase (0 - not visited, 1 - visited, 2 - ??? (...))
     */

    Cell(){
        walls = new boolean[]{true, true, true, true}; // {N, S, E, W}
        vis = false;
        value = 0;
    }
}

class Maze{

    /*
        Maze class was created in order to generate an array of Cells,
        that will be later used in the algorithm.

        First we create integer ,,size,, to store size of the array, then
        we create a matrix, that will hold Cell objects.

        In the constructor of the class, we set the required integer s as size,
        allocate memory to the matrix, by setting its dimensions to size x size
        and we create Cell objects for each spot int the matrix, without any modifications.
     */



    int size;
    Cell[][] matrix;


    Maze(int s){
        size = s;
        matrix = new Cell[size][size];
        
        for(int y = 0; y < size; y++){
            for(int x = 0; x < size; x++){
                matrix[y][x] = new Cell();
                //System.out.print("1");
            }
        }
    }


    void showMaze(){
        for(int y = 0; y < size; y++){
            for(int x = 0; x < size; x++){
                System.out.print(matrix[y][x].getValue() + " ");
            }
            System.out.println();
        }
    }



    /*
        Class ,,MazeAlgorithm'' is responsible for creating connections between cells in matrix.
        It uses RBT, which stands for Recursive Back-Tracker, to achieve that goal.
        In order to use RBT, we need to give it starting point. After we do that,
        it will check, if there is any neighbour, that fulfills the required conditions,
        and then goes to that neighbour setting visited to true and value to 1.
        After that, it repeats the process, and constantly adds the cells coordinates
        on top of the stack, to keep track of the road it went through. If it gets stuck,
        it will go back to the previous cell, by removing the top coordinates of the stack,
        and going to NOW top coordinates (previous move), checking if that cell has any
        neighbours which can fulfill the conditions. If it cannot find any neighbour,
        it means the maze was created.
     */


    void RBT(int startX, int startY){

        //Setting cells to visit to size x size, and the value of visited cells to 0
        int toVis = size*size;
        int vis = 0;


        //Declaring a stack, that will hold the information about our road
        Stack<Pair<Integer, Integer>> stack = new Stack<>();


        //Setting starting position: pushing it onto the stack,
        //setting it's values as visited and 1,
        //incrementing visited rooms.
        stack.push(new Pair<>(startX, startY));

        matrix[startY][startX].vis = true;
        matrix[startY][startX].value = 1;
        vis += 1;

        //we will check, if our current node has any neighbours we can go to,
        //saving those neighbours inside a vector
        while(vis < toVis){
            Vector<Integer> neighbours = new Vector<>();
            int x = stack.firstElement().getKey();
            int y = stack.firstElement().getValue();


            //North neighbour
            if(y-1 >= 0 && !matrix[y - 1][x].vis){
                neighbours.add(0);
            }

            //South neighbour
            if(y+1 < size && !matrix[y + 1][x].vis){
                neighbours.add(1);
            }

            //East neighbour
            if(x+1 < size && !matrix[y][x + 1].vis){
                neighbours.add(2);
            }

            //West neighbour
            if(x-1 >= 0 && !matrix[y][x - 1].vis){
                neighbours.add(3);
            }


            //checking, if there are any neighbours we can visit
            //if yes, we do our job
            //if not, we pop our stack and repeat the process
            if(!neighbours.isEmpty()){
                Random rand = new Random();
                int randDir = neighbours.get(rand.nextInt(neighbours.size()));

                switch (randDir) {
//North
                    case 0 -> {

                        matrix[y][x].walls[0] = false;

                        stack.push(new Pair<>(x, y - 1));

                        matrix[y - 1][x].value = 1;
                        matrix[y - 1][x].vis = true;
                        matrix[y - 1][x].walls[1] = false;

                    }
//South
                    case 1 -> {
                        matrix[y][x].walls[1] = false;

                        stack.push(new Pair<>(x, y + 1));

                        matrix[y + 1][x].value = 1;
                        matrix[y + 1][x].vis = true;
                        matrix[y + 1][x].walls[0] = false;
                    }
//East
                    case 2 -> {
                        matrix[y][x].walls[2] = false;

                        stack.push(new Pair<>(x + 1, y));

                        matrix[y][x + 1].value = 1;
                        matrix[y][x + 1].vis = true;
                        matrix[y][x + 1].walls[3] = false;
                    }
//West
                    case 3 -> {
                        matrix[y][x].walls[3] = false;

                        stack.push(new Pair<>(x - 1, y));

                        matrix[y][x - 1].value = 1;
                        matrix[y][x - 1].vis = true;
                        matrix[y][x - 1].walls[2] = false;
                    }
                }

                vis += 1;
            }else{
                stack.pop();
            }
        }
    }
}

public class MazeAlgorithm {


    public static void main(String[] args){

        Maze m = new Maze(3);
        m.RBT(1, 1);
        m.showMaze();
    }

so i just run the code again, and the error line changed to line 131, i am also watching some tutorial about the Intellij debugger rn.


Solution

EDIT: Problem resolved. Had to change lines:

 int x = stack.firstElement().getKey();   
 int y = stack.firstElement().getValue();

into:

 int x = stack.peek().getKey();   
 int y = stack.peek().getValue();

Turns out method .firstElement() doesn't give you first element (the one on top of the stack) but the one that was first inserted (always the same object) so in the end all the operation were performed on one, single element and not multiple ones.



Answered By - 22eragon22
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 15, 2022

[FIXED] Why isn't my output showing after my switch statement

 August 15, 2022     java, output, switch-statement     No comments   

Issue

I'm learning Java right now and I've never used switch statements before. I tried to enter a simple charmed quiz, but something in the switch statement isn't working.

I've tried putting text at various points in the program to test if the program every reaches that code. I have a good response inside the actual switch, so If I answer Question 1 wrong the text prompt will show up. But any later than inside the switch statement and none of my scoring output appears until all iterations of the for loop are complete. I have tried moving the "correct/incorrect" output to various points and none of them seem to work.

Scanner myScanner = new Scanner(System.in);

System.out.println("Enter your name!");
String name = myScanner.nextLine();
int wrongCounter = 0;
boolean correctChecker = false;
int score = 0;
String answer;

System.out.println("Welcome to the Charmed Quiz, " + name + "!");

for (int i = 0; i < 10; i++) {
    if (wrongCounter < 4) {
        switch(i) {
        case 0: 
            System.out.println("Who read the spell that gave the Charmed Ones their powers?");
            System.out.println("Enter your answer");

            answer = myScanner.nextLine();

            switch (answer) {
            case "Pheobe":
                correctChecker = true;
                break;
            default:
                correctChecker = false;
                break;
            }
        case 1:
            System.out
                    .println("Who travelled to a cursed town with Prue when Pheobe was shot in a premonition?");
            System.out.println("Enter your answer");

            answer = myScanner.nextLine();

            switch (answer) {
            case "Cole":
                correctChecker = true;
                break;
            default:
                correctChecker = false;
                break;
            }
        }
        
    

    if (correctChecker == true) {
        score++;
        System.out.println("Correct!");
    } else {
        wrongCounter++;
        System.out.println("Incorrect!");

    }

Solution

This definitely isn't the best way of achieving a quiz game, but if you're using this as a learning exercise then the best course of action is to take the advice from @rzwitserloot.

Add a break after your main switch statement cases as opposed to the inner switch statement.

There is no real use having an inner switch statement though when you can use correctChecker = "Pheobe".equals(answer); to get a true or false boolean value in a single line.

This just means you can avoid the second switch statement which makes it way less confusing.

Altogether your cases could look something like this:

    case 0: 
        System.out.println("Who read the spell that gave the Charmed Ones their powers?");
        System.out.println("Enter your answer");

        answer = myScanner.nextLine();
        correctChecker = "Pheobe".equals(answer);
        break;
        
        }

In future, it would be better to store questions and answers in an array and use the for loop to iterate through that. This is a good tutorial on the subject.

Good luck with the rest of your project!



Answered By - o.no
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, June 26, 2022

[FIXED] Why is my code expecting a primary expression in a switch case before curly brackets?

 June 26, 2022     c++, compiler-errors, enums, switch-statement     No comments   

Issue

I am trying to use a switch case as a sort of menu selection for the user in my code. I have this enum list:

enum menuChoice {ADD = 1, REMOVE = 2, DISPLAY = 3, SEARCH = 4, RESULTS = 5, QUIT = 6};

Then I have this code:

        menuChoice switchChoice;
        Student student;

        cout << "1. Add\n" << "2. Remove\n" << "3. Display\n" << "4. Search\n";
        cout << "5. Results\n" << "6. Quit" << endl;

        for (int i = 0; i < 999; ++i)
        {
                cout << "Please enter choice:";

                cin >> userChoice;

                if (userChoice > 6 || userChoice < 1)
                {
                        cout << "Incorrect choice. Please enter again" << endl;
                }
                else
                {
                        break;
                }
        }

        switchChoice = static_cast<menuChoice>(userChoice);
        switch(switchChoice){

        case 1:
                add_Student(student);

                break;
        case 2:

                break;
        case 3:

                break;
        case 4:

                break;
        case 5:

                break;
        case 6:
                break;

        default:
        }

Which is kicking back this error:

 error: expected primary-expression before ‘}’ token

I am really scratching my head over this. What is the mistake here? How am I not implementing a primary expression? I know that you aren't supposed to pass types to switch parameters but this is an enum variable I'm passing. Some help on this would be greatly appreciated.


Solution

default: } is a syntax error. The default label must be followed by a statement or a block. (This applies to any othe sort of label too).

For example it could be default: break; or default: ; or default: {} .



Answered By - M.M
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, May 17, 2022

[FIXED] Which is the best/fastest practice? Create the same loop in each case of a switch statement, or to switch the same case of a for loop?

 May 17, 2022     arrays, for-loop, php, switch-statement     No comments   

Issue

So I was about to write something like following code

switch ($mode) {
    case 'all':
        foreach ($sortInfo as $info) $filter[] = array_merge([$info->maincat], $info->subcats);
        break;
    case 'sub':
        foreach ($sortInfo as $info) $filter[] = $info->subcats;
        break;
    default:
        foreach ($sortInfo as $info) $filter[] = [$info->maincat];
        break;
}

Then I told myself "hey, wouldn't it be more optimized if I wrapped the whole switch inside the for loop?"

foreach ($sortInfo as $info) {
    switch ($mode) {
        case 'all':
            $filter[] = array_merge([$info->maincat], $info->subcats);
            break;
        case 'sub':
            $filter[] = $info->subcats;
            break;
        default:
            $filter[] = [$info->maincat];
            break;
    }
}

But while it does technically save a bit (get it?) of filesize, the loop would confirm the same information in the switch statement for each iteration of the loop.

I figured there is no objective way to determine which is fastest because it depends on the length of $sortinfo, but since it's the first time I come across this dilemma, I'd like to know if there's a preferred method, or what's your take on it.


Solution

Since you will only be running this once, any performance difference is entirely negligible. You could benchmark with a fixed dataset if you had to run it thousands of times, though still I doubt that you'd see more than a +/- 10% difference. Choose whichever version you find more readable. If you want to save bits and are running PHP 8, you can do:

$cats = match($mode) {
    'all' => array_merge(
        array_column($sortInfo, 'maincat'), ...array_column($sortInfo, 'subcats')
    ),
    'sub' => array_merge(...array_column($sortInfo, 'subcats')),
    default => array_column($sortInfo, 'maincat')
};

Updated: Per OP's revision, maincat is a single scalar and subcats is an array of scalars. Since we want to have a 1-D array in all modes, we use the ... splat operator to "dish out" the subcategories into the array_merge, which gives us a "flat" array. Demo: 3v4l.org/NasiC

That's 227 bits vs. 338 bits in your "switch in foreach" vs. 346 bits in your "foreach in switch" or a 33% reduction. I find this approach very readable and free of avoidable verbosity.

If you're still runnning PHP 7, you can factor this approach into a switch:

switch ($mode) {
    case 'all': 
        $cats = array_merge(
            array_column($sortInfo, 'maincat'), ...array_column($sortInfo, 'subcats')
        );
    break;
    case 'sub': 
        $cats = array_merge(...array_column($sortInfo, 'subcats'));
        break;
    default: 
        $cats = array_column($sortInfo, 'maincat');
        break;
};

That's still only 299 bytes. :) N.B. match was one of my major reasons for upgrading early to PHP 8. Premium sugar for a number of dishes, eliminates a lot of boilerplate code.



Answered By - Markus AO
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, April 28, 2022

[FIXED] Why is JSLint warning me about my switch-case statement being incorrectly formatted?

 April 28, 2022     adobe-brackets, javascript, jslint, switch-statement, warnings     No comments   

Issue

In Adobe Brackets, I am getting warnings from JSLint when writing strict code ['use strict'] that my switch case statement is incorrectly formatted:
eg. Expected 'case' at column #, not column #

If I move everything inside the switch statement back back one "tab" JSLint is happy.
But, Adobe Brackets (And Similar Code Applications) wants to indent the case statements, and even when using Code Beautify it also formats the code to have an indent before the case statement.

  • When using strict code, is what JSLint is suggesting really the proper way of to format the switch-case statements?
  • Is there a way to fix/make JSLint in Adobe Brackets so it thinks this indentation is correct? (I would like to stick to not hacking up the JSLint Code)
  • Why would Editors format the switch-case statement this way if strict code does not want you to do that?
  • Am I really just doing something wrong here?
  • Is this just a downside of JSLint and is there a way to avoid using the switch-case statement then altogether thus in the process also making JSLint happy?
  • Should I really just stop using JSLint altogether? And Switch to something else?

This Code is nested in a for loop:

switch (curButton.button.innerText.toLowerCase()) {
    case this.Part1.Button.ButtonText.toLowerCase():
        this.Part1.Button.ButtonText = curButton.button.innerText;
        this.Part1.Button.Element = curButton.button;
        this.Part1.Button.CurrentClass = curButton.button.className;
        console.log(smgData.PodCast.Parts.Part1.Button);
        break;
    case this.Part2.Button.ButtonText.toLowerCase():
        this.Part2.Button.ButtonText = curButton.button.innerText;
        this.Part2.Button.Element = curButton.button;
        this.Part2.Button.CurrentClass = curButton.button.className;
        console.log(smgData.PodCast.Parts.Part2.Button);
        break;
    case this.Part3.Button.ButtonText.toLowerCase():
        this.Part3.Button.ButtonText = curButton.button.innerText;
        this.Part3.Button.Element = curButton.button;
        this.Part2.Button.CurrentClass = curButton.button.className;
        console.log(smgData.PodCast.Parts.Part3.Button);
        break;
}

Here is some basic code that will reproduce this on https://www.jslint.com/

function abcd() {
    var a;
    var b;
    switch (a) {
        case 1:
            a=b;
            break;
        case 2:
            b=a;
            break;
    }
}

JSLint Warnings


Solution

This sounds like a problem with JSLint.

It's not exactly what you were asking, but one way to re-formulate the code and avoid switch entirely (and thus the problems JSLint has with switch) is to .find the Part whose ButtonText matches. Then use bracket notation to look up the button on the this:

const currentText = curButton.button.innerText.toLowerCase();
const matchingPart = ['Part1', 'Part2', 'Part3']
    .find(part => currentText === this[part].Button.ButtonText.toLowerCase());
if (matchingPart) {
    const { button } = this[matchingPart];
    button.ButtonText = curButton.button.innerText;
    button.Element = curButton.button;
    button.CurrentClass = curButton.button.className;
    console.log(smgData.PodCast.Parts[matchingPart].Button);
}

If you can control the shape of the this object, it would probably be easier if the Parts were an array, instead of 3 different properties. Then, you could .find over that array, instead of hard-coding the 3 Part properties.

I'd consider the code above to be perfectly fine, but to make it pass all of JSLint's (IMO - opinionated and not-so-good) rules, it'd have to be

const currentText = curButton.button.innerText.toLowerCase();
const props = ["Part1", "Part2", "Part3"];
const matchingPart = props.find(function(part) {
    return currentText === this[part].Button.ButtonText.toLowerCase();
});
if (matchingPart) {
    const { button } = this[matchingPart];
    button.ButtonText = curButton.button.innerText;
    button.Element = curButton.button;
    button.CurrentClass = curButton.button.className;
    console.log(smgData.PodCast.Parts[matchingPart].Button);
}


Answered By - CertainPerformance
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the meaning of the GCC warning "case label value exceeds maximum value for type"?

 April 28, 2022     c, gcc, switch-statement, warnings     No comments   

Issue

My code looks like this:

char * decode_input(char ch)
{
        switch(ch) {
                case 'g':
                        return "get";
                        break;
                case KEY_F(9):
                        return "quit";
                        break;
                default:
                        return "unknown";
                        break;
        }
}

Any clues?


Solution

A char is a number between -128 and 127. KEY_F(9) probably is a value outside of that range.

Use:

  • unsigned char, or
  • int, or
  • (char) KEY_F(9)

Or even better, use a debugger and determine sizeof(KEY_F(9)) to make sure it's a byte and not a short.



Answered By - razzed
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 16, 2022

[FIXED] Using comparison operators in a PHP 'switch' statement

 March 16, 2022     php, switch-statement     No comments   

Issue

I have four conditions that I need to go through and I thought it would be best to use the switch statement in PHP. However, I need to check whether an integer is, let's say, less than or equal, or greater than and equal.

switch ($count) {
    case 20:
        $priority = 'low';
        break;

    case 40:
        $priority = 'medium';
        break;

    case 60:
        $priority = 'high';
        break;

    case 80:
        $priority = 'severe';
        break;
}

With an if() statement it would look like the following:

if ($count <= 20) {
    $priority = 'low';
} elseif ($count <= 40) {
    $priority = 'medium';
} elseif ($count <= 60) {
    $priority = 'high';
} else {
    $priority = 'severe';
}

Is that possible in switch-case?


Solution

A more general case for solving this problem is:

switch (true) {
    case $count <= 20:
        $priority = 'low';
        break;

    case $count <= 40:
        $priority = 'medium';
        break;

    case $count <= 60:
        $priority = 'high';
        break;

    default:
        $priority = 'severe';
        break;
}


Answered By - Konr Ness
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, January 13, 2022

[FIXED] PHP switch statement problem causes a syntax error

 January 13, 2022     php, php-7.4, switch-statement     No comments   

Issue

My code:

<?php
    $i = 1;
    switch ($i) {
?>
        
        <?php
            case 1:
        ?>
        $i is 1
        <?php
            break;
        ?>
<?php
    }
?>

This code gives me an error:

Parse error: syntax error, unexpected ' ', expecting case (T_CASE) or default (T_DEFAULT) or '}' in D:\xampp\htdocs\php-mvc\public\test.php on line 5

I know that I can avoid closing php tags and say echo 'text'; but still, how to fix this?


Solution

You are breaking the switch syntax off by outputting empty spaces when closing and opening the PHP tag.

This will work:

<?php
    $i = 1;
    switch ($i) {
            case 1:
        ?>
        $i is 1
        <?php
            break;
        ?>
<?php
    }
?>


Answered By - thephper
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing