Java 尝试根据用户输入使用具有不同参数的 switch 语句创建对象

Java trying to create an object using switch statement with different parameters based on user input

所以我正在使用 Java 制作一个文字冒险 RPG,我想使用一个 switch 语句来获取用户的下一个输入并创建我的 class、FTAWeapon 的实例, 根据用户的输入使用不同的参数。

例如,如果用户输入“1”,我想创建一个名为 weapon 的 FTAWeapon 实例,参数为 (1, 6, 1, 5, 8, .75)。

但是如果用户改为输入“2”,我想创建一个 FTAWeapon 实例,仍然命名为 weapon,参数为 (2, 24, 3, 7, 15, .65)。

但是,我得到这个错误:

错误:变量 weapon 已经在方法 main(String[]) 中定义

此错误出现 4 次,在第一次创建对象实例之后的所有尝试中。

这是给我问题的代码:

switch(kb.next())
           {
              case "1":
                 System.out.println("\n\n*.44 Magnum Revolver added to inventory*");
                 FTAWeapon weapon = new FTAWeapon(1, 6, 1, 5, 8, .75);
                 break;

              case "2":
                 System.out.println("\n\n*Assault Rifle added to inventory*");
                 FTAWeapon weapon = new FTAWeapon(2, 24, 3, 7, 15, .65);
                 break;

              case "3":
                 System.out.println("\n\n*Laser Pistol added to inventory*");
                 FTAWeapon weapon = new FTAWeapon(3, 30, 1, 2, 6, .85);
                 break;

              case "4":
                 System.out.println("\n\n*Caravan Shotgun added to inventory*");
                 FTAWeapon weapon = new FTAWeapon(4, 14, 7, 3, 20, .50);
                 break;

              case "5":
                 System.out.println("\n\n*Plasma Rifle added to inventory*");
                 FTAWeapon weapon = new FTAWeapon(5, 24, 1, 5, 10, .70);
                 break;
           }
FTAWeapon weapon = null; // Declaration outside the switch statement
switch(kb.next())
{
          case "1":
             System.out.println("\n\n*.44 Magnum Revolver added to inventory*");
             weapon = new FTAWeapon(1, 6, 1, 5, 8, .75);
             break;

          case "2":
             System.out.println("\n\n*Assault Rifle added to inventory*");
             weapon = new FTAWeapon(2, 24, 3, 7, 15, .65);
             break;

          case "3":
             System.out.println("\n\n*Laser Pistol added to inventory*");
             weapon = new FTAWeapon(3, 30, 1, 2, 6, .85);
             break;

          case "4":
             System.out.println("\n\n*Caravan Shotgun added to inventory*");
             weapon = new FTAWeapon(4, 14, 7, 3, 20, .50);
             break;

          case "5":
             System.out.println("\n\n*Plasma Rifle added to inventory*");
             weapon = new FTAWeapon(5, 24, 1, 5, 10, .70);
             break;
}

每个 case 子句中的变量范围对应于整个 switch 语句。