Hi all,

Can some please have a look at the codes below and tell how I can make the switch statement accept the value from the variable named answer. I think the switch statement only accepts certain data type but I don't know to make this work.

Please help me with this problem. Thank you.

package game;

import java.util.*;
import java.io.*;

public class GameInfo
{
    private ArrayList<Game> games = new ArrayList<Game>();//Array to store game Info, Name and Type

    private GameInfo()//game array
    {
        games.add( new Game ("RPG", "EVE Online",
                        "EVE is a sci-fi massively multiplayer online game. " +
                        "Players take the role of spaceship pilots seeking " +
                        "fame, fortune, and adventure in a huge, complex, " +
                        "exciting, and sometimes hostile galaxy."));
        games.add( new Game ("RPG", "Dark Ages",
                        "Dark Ages is an online role-playing game set in a " +
                        "fantasy world of faeries and magic. Customize your " +
                        "character and go adventuring." ) );
        games.add( new Game ("RPG", "City of Heroes",
                        "City of Heroes brings the world of comic books " +
                        "alive. Craft your hero's identity and join millions " +
                        "of Hero characters in a constantly expanding " +
                        "universe, explore the sprawling online metropolis " +
                        "of Paragon City, and battle a host of foes " +
                        "including criminals, villains, and monsters."));
        games.add( new Game ("Simulation", "King of Drift",
                        "Race around the track as you try to win against the " +
                        "AI. Drift around corners for an advantage" ) );
        games.add( new Game("Simulation", "Jet Ski Rush",
                        "Drive your jet-ski through the wavey waters and " +
                        "complete all 10 extreme levels! Hop over gators, " +
                        "hippos, penguins to hit ramps and do tricks! Grab " +
                        "NOS to speed up through super loops! " ) );
   		games.add( new Game("FPS", "Hover Tanks",
                        "Blast away at your opponents to set a highscore in " +
                        "this awesome 3D first-person shooter." ) );
  		games.add( new Game("FPS", "Pearl Habour 1941",
                        "Shoot all incoming Kamikaze pilots and protect " +
                        "Pearl Habour") );

        InputStreamReader istream = new InputStreamReader(System.in) ;
        BufferedReader bufRead = new BufferedReader(istream) ;

        System.out.println("------------------------\nTypes of Games available\n------------------------");
        System.out.println();

        try
        {
            System.out.println("Please enter a choise based on the following available game types");
            System.out.println("(1) First Person Shooter");
            System.out.println("(2) Role Palaying Games");
            System.out.println("(3) Simulation games");
            String chooseType = bufRead.readLine();
            int cType = Integer.parseInt(chooseType);
            int answer = cType;

            

            switch (answer)
        {
            case '1':
                System.out.println("--------------------------\nFirts Person Shooter Games\n--------------------------");
                for ( int i = 0; i < games.size(); i++)
        {
            if ( games.get(i).getType().equals("FPS"))
            {
                System.out.println(games.get(i).toString());
            }
        }
                break;

            case '2':
                System.out.println("------------------\nRole Playing Games\n------------------");
        for ( int i = 0; i < games.size(); i++)
        {
            if ( games.get(i).getType().equals("RPG"))
            {
                System.out.println(games.get(i).toString());
            }
        }
                break;

            case '3':
                System.out.println("----------------\nSimulation Games\n----------------");
        for ( int i = 0; i < games.size(); i++)
        {
            if ( games.get(i).getType().equals("Simulation"))
            {
                System.out.println(games.get(i).toString());
            }
        }
                break;

            default:
                System.out.println("Please press 1, 2 or 3");
        }

        }

        catch (IOException err)
        	{
               System.out.println("Error reading line");
            }
    }

      public static void main(String[] args)// main method to start the program
    {
        new GameInfo();
    }
}

Recommended Answers

All 6 Replies

You're very close. Problem is that you parse the input to get an int value 1,2,3 but in the switch you look for values '1', '2', '3'. These values are type char, not int, and are the Unicode/ASCII values for those letters.
Just drop the quote marks (ie case 1: ) and you'll be well on yor way to the next problem :-)

Hi James Cherrill,

Thank you so much for your help, it works now.

Someone from another forum advised me to do it as the codes below, but I can't seem to get it working at all.

This is what I get when I run the codes.

run:
Please enter a choise based on the following available game types stored in database
(0) RPG
(1) Simulation
(2) FPS
1
BUILD SUCCESSFUL (total time: 5 seconds)

It exits without displaying the games of type chosen.

The program suppose to update name of game chosen, but that too is not working as expected.

Can you please have a look at these codes and tell me how I can make it work. And in your opinion which one is better, the one with the switch statement or the one below.

Game Class

package game;

class Game
{
    private String type, name, description;

    public Game( String gType, String gName, String gDescription )
    {
        type = gType;
        name = gName;
        description = gDescription;
    }
    
    public String getType()
    {
        return type;
    }

    public String getName()
    {
        return name;
    }

    public void setName( String gNew )
    {
        name = gNew;
    }

    public void updateDescription( String gNew )
    {
        description = gNew;
    }

    public void updateType( String gNew )
    {
        type = gNew;
    }
    
    @Override
    public String toString()
    {
        return ( "Game Title \t:: " + name + "\nGame Description   :: " + description);
    }
}

GameInfo Class

package game;

import java.util.*;

public class GameInfo
{
    private ArrayList<Game> games = new ArrayList<Game>();//Array to store game Info, Name and Type
    private ArrayList<String> availableTypes = new ArrayList<String>();//Array to store game Type

    private void changeName( String gName, String gNew ) //method to update game information
    {
        for ( int i = 0; i < games.size(); i++)
        {
            if (games.get(i).getName().equals(gName))
            {
                games.get(i).setName( gNew);
                return;
            }
        }
        System.out.println("Game not found");        
    }

    private GameInfo()//game array
    {            
        games.add( new Game ("RPG", "EVE Online",
                        "EVE is a sci-fi massively multiplayer online game. " +
                        "Players take the role of spaceship pilots seeking " +
                        "fame, fortune, and adventure in a huge, complex, " +
                        "exciting, and sometimes hostile galaxy."));
        games.add( new Game ("RPG", "Dark Ages",
                        "Dark Ages is an online role-playing game set in a " +
                        "fantasy world of faeries and magic. Customize your " +
                        "character and go adventuring." ) );
        games.add( new Game ("RPG", "City of Heroes",
                        "City of Heroes brings the world of comic books " +
                        "alive. Craft your hero's identity and join millions " +
                        "of Hero characters in a constantly expanding " +
                        "universe, explore the sprawling online metropolis " +
                        "of Paragon City, and battle a host of foes " +
                        "including criminals, villains, and monsters."));
        games.add( new Game ("Simulation", "King of Drift",
                        "Race around the track as you try to win against the " +
                        "AI. Drift around corners for an advantage" ) );
        games.add( new Game("Simulation", "Jet Ski Rush",
                        "Drive your jet-ski through the wavey waters and " +
                        "complete all 10 extreme levels! Hop over gators, " +
                        "hippos, penguins to hit ramps and do tricks! Grab " +
                        "NOS to speed up through super loops! " ) );
   	games.add( new Game("FPS", "Hover Tanks",
                        "Blast away at your opponents to set a highscore in " +
                        "this awesome 3D first-person shooter." ) );
  	games.add( new Game("FPS", "Pearl Habour 1941",
                        "Shoot all incoming Kamikaze pilots and protect " +
                        "Pearl Habour") );
        
        //game type array
        availableTypes.add("RPG");
        availableTypes.add("Simulation");
        availableTypes.add("FPS");

        //method for receiving user input
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a choise based on the following available game types stored in database");
        //to display available game types
        for ( int i = 0; i < availableTypes.size(); i++)
        {
            System.out.println("(" + i + ") " + availableTypes.get(i));
        }
        int choice = input.nextInt();
        for ( int i = 0; i < games.size(); i++) {
            if (games.get(i).getType().equals(availableTypes.get(choice))) {
            }
        }

        changeName("King of Drift", "King of Drift - The King");// method to update game infomation
        
    }

      public static void main(String[] args)// main method to start the program
    {
        new GameInfo();
    }
}

Hi. That other way of doing it is OK too. In my opinion the switch version is easier to understand and maintain, but other people may disagree.
It's not working because in the if statement on line 72 (where you find the matching games) it doesn't actually do anything! It should be

for ( int i = 0; i < games.size(); i++) {
  if (games.get(i).getType().equals(availableTypes.get(choice))) {
    //print something about games.get(i)
  }
}

However, sinve Java 1.5 there's a much better way to write loops like that

for (Game g : games) {
  if (g.getType().equals(availableTypes.get(choice))) {
     // print something about g
  }
}

Hi JamesCherrill,

I have fixed the code and added some more, could you please tell me how I could make it display the Game Title and Game Description of the game that I updated as in line number 113. Any other advice you can give me is most welcomed.

Thank you very much.

package game;

import java.util.*;
import java.io.*;

public class GameInfo
{
    private ArrayList<Game> games = new ArrayList<Game>();//Array to store game Info, Name and Type
    private ArrayList<String> availableTypes = new ArrayList<String>();//Array to store game Type

    private void changeName( String gName, String gNew ) //method to update game information
    {
        for ( int i = 0; i < games.size(); i++)
        {
            if (games.get(i).getName().equals(gName))
            {
                games.get(i).setName( gNew);
                return;
            }
        }
        System.out.println("Game not found");
    }

    private GameInfo()//game array
    {
        games.add( new Game ("RPG", "EVE Online",
                        "EVE is a sci-fi massively multiplayer online game. " +
                        "Players take the role of spaceship pilots seeking " +
                        "fame, fortune, and adventure in a huge, complex, " +
                        "exciting, and sometimes hostile galaxy."));
        games.add( new Game ("RPG", "Dark Ages",
                        "Dark Ages is an online role-playing game set in a " +
                        "fantasy world of faeries and magic. Customize your " +
                        "character and go adventuring." ) );
        games.add( new Game ("RPG", "City of Heroes",
                        "City of Heroes brings the world of comic books " +
                        "alive. Craft your hero's identity and join millions " +
                        "of Hero characters in a constantly expanding " +
                        "universe, explore the sprawling online metropolis " +
                        "of Paragon City, and battle a host of foes " +
                        "including criminals, villains, and monsters."));
        games.add( new Game ("Simulation", "King of Drift",
                        "Race around the track as you try to win against the " +
                        "AI. Drift around corners for an advantage" ) );
        games.add( new Game("Simulation", "Jet Ski Rush",
                        "Drive your jet-ski through the wavey waters and " +
                        "complete all 10 extreme levels! Hop over gators, " +
                        "hippos, penguins to hit ramps and do tricks! Grab " +
                        "NOS to speed up through super loops! " ) );
   	games.add( new Game("FPS", "Hover Tanks",
                        "Blast away at your opponents to set a highscore in " +
                        "this awesome 3D first-person shooter." ) );
  	games.add( new Game("FPS", "Pearl Harbour 1941",
                        "Shoot all incoming Kamikaze pilots and protect " +
                        "Pearl Habour") );

        //game type array
        availableTypes.add("RPG");
        availableTypes.add("Simulation");
        availableTypes.add("FPS");

        //method for receiving user input
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a choise to display games by type or press (c) to change a game detail");
        
        //to display available game types
        for ( int i = 0; i < availableTypes.size(); i++)
        {
            System.out.println("(" + i + ") " + availableTypes.get(i));
        }
        int choice = input.nextInt();
        for ( int i = 0; i < games.size(); i++)
        {
            if (games.get(i).getType().equals(availableTypes.get(choice))) 
            {
                System.out.println( games.get(i).toString() );
            }
        }

        // method to update game infomation
        String oriName = "";
        String newName = "";
        InputStreamReader nameInput = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(nameInput);
        System.out.println();
        System.out.println("Type the title of the game to update");
        System.out.println();
        try
        {
            oriName = reader.readLine();
        }
        
        catch (IOException err)
        {
               System.out.println("Error reading line");
        }
        
        System.out.println();
        System.out.println("Type the new title for the game");

        try
        {
            newName = reader.readLine();
        }
        
        catch (IOException err)
        {
               System.out.println("Error reading line");
        }
        
        changeName(oriName, newName);
        System.out.println("Game Title \t:: " + newName + "\nGame Description   :: " + description);
    }

      public static void main(String[] args)// main method to start the program
    {
        new GameInfo();
    }
}

This is how it shows up now

run:
Please enter a choice to display games by type or press (c) to change a game detail
(0) RPG
(1) Simulation
(2) FPS
2
Game Title :: Hover Tanks
Game Description :: Blast away at your opponents to set a highscore in this awesome 3D first-person shooter.
Game Title :: Pearl Harbour 1941
Game Description :: Shoot all incoming Kamikaze pilots and protect Pearl Harbour

Type the title of the game to update

Hover Tanks

Type the new title for the game
Hover 2
Game Title :: Hover 2
BUILD SUCCESSFUL (total time: 30 seconds)


I would like it to show like this

run:
Please enter a choice to display games by type or press (c) to change a game detail
(0) RPG
(1) Simulation
(2) FPS
2
Game Title :: Hover Tanks
Game Description :: Blast away at your opponents to set a highscore in this awesome 3D first-person shooter.
Game Title :: Pearl Harbour 1941
Game Description :: Shoot all incoming Kamikaze pilots and protect Pearl Harbour

Type the title of the game to update

Hover Tanks

Type the new title for the game
Hover 2
Game Title :: Hover 2
Game Description :: Blast away at your opponents to set a highscore in this awesome 3D first-person shooter.

I got it working. Please advice if its the proper way. I added these codes to line 113

for ( int i = 0; i < games.size(); i++)
        {
            if (games.get(i).getType().equals(availableTypes.get(choice)))
            {
                System.out.println( games.get(i).toString() );
            }
        }

I haven't gone thru all your code, but that looks sensible.
ps You don't need the toString() in a print - the print method calls it automatically. YOu can just say
System.out.println( games.get(i));

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.