How can I improve this code so that there are no errors due to having multiple objects with the same name?

Rellik :

I want to make a text-based game, and I want to make it so the player chooses what ship they will pilot. Then after they pick a ship, whatever code I have after will reference the same object name as all other player-specific ships.

I have tried multiple google searches, but nothing seems to help. This is my first game that I will attempt to make, and no matter what I do I can't seem to rectify this issue

//Ignore all the ship.setupShip stuff that isnt causing me an issue

switch (shipSelector) {
            case 1:
                Frigate ship = new Frigate();
                System.out.println("Give your ship a name!");
                String shipNamer = keyboard.nextLine();
                ship.setupShip("Frigate", shipNamer);
                break;
            case 2:
                Shuttle ship = new Shuttle();
                System.out.println("Give your ship a name!");
                String shipNamer = keyboard.nextLine();
                ship.setupShip("Frigate", shipNamer);
                break;
            case 3:
                Cruiser ship = new Cruiser();
                System.out.println("Give your ship a name!");
                String shipNamer = keyboard.nextLine();
                ship.setupShip("Frigate", shipNamer);
                break;
            default:
                break;
        }

I want it to be so that I can have one name reference for all player ships since the basic part of the game won't need the specific types of ship.

The only error I get is:

Error:(49, 25) java: variable ship is already defined in method main(java.lang.String[])
jack :

Variable ship is already defined , like this:

switch (shipSelector) {
            case 1:
                Frigate ship1 = new Frigate();
                System.out.println("Give your ship a name!");
                String shipNamer = keyboard.nextLine();
                ship1.setupShip("Frigate", shipNamer);
                break;
            case 2:
                Shuttle ship2 = new Shuttle();
                System.out.println("Give your ship a name!");
                String shipNamer = keyboard.nextLine();
                ship2.setupShip("Frigate", shipNamer);
                break;
            case 3:
                Cruiser ship3 = new Cruiser();
                System.out.println("Give your ship a name!");
                String shipNamer = keyboard.nextLine();
                ship3.setupShip("Frigate", shipNamer);
                break;
            default:
                break;
        }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=153487&siteId=1