首页 > 解决方案 > 允许用户输入具有相同名称的变量

问题描述

我目前正在使用 charAt(0) 方法来允许用户进行输入。这是一个问题,因为我有一个以相同字符开头的变量。在这种情况下,我希望程序读取前 3 个字符。换句话说,如何确保我的程序在选择时识别正确的变量?

PS-我知道我需要研究命名约定,我还是 Java 新手并且正在学习。

switch(SkillChoice.nextLine().toLowerCase().charAt(0)){
        case 'd':
            System.out.println("How many points towards Dexterity?");
            System.out.println("Your current Dexterity is " + Attribute.Dexterity);

            SkillChoice.nextDouble();

            Attribute.setDex(SkillChoice.nextDouble() + Attribute.getDex());
            System.out.println(Attribute.Dexterity);
        case 's':
            System.out.println("How many points towards Strength?");
            System.out.println("Your current Strength is " + Attribute.Strength);

        SkillChoice.nextDouble();

            Attribute.setStr(SkillChoice.nextDouble() + Attribute.getStr());
            System.out.println(Attribute.Strength);
        case 's':
            System.out.println("How many points towards Strength?");
            System.out.println("Your current Strength is " + Attribute.Stamina);

             SkillChoice.nextDouble();

            Attribute.setSta(SkillChoice.nextDouble() + Attribute.getSta());
            System.out.println(Attribute.Dexterity);
        case 'i':
            System.out.println("How many points towards Intelligence?");
            System.out.println("Your current Intelligence is " + Attribute.Intelligence);

            SkillChoice.nextDouble();

            Attribute.setInt(SkillChoice.nextDouble() + Attribute.getInt());
            System.out.println(Attribute.Intelligence);

出现提示时,用户应该能够键入“Str****”或“Sta****”,其中 * 是任何字符串组合,程序应该将其识别为想要增加力量或耐力点。

标签: java

解决方案


我认为您应该摆脱整个开关/案例代码并坚持使用if子句。那是因为我在下面解释的内容不适用于switch/case,如果你真的想坚持使用它,你至少应该查找正确的语法,因为你错过了任何中断

这样你就可以简单地使用String类的方法startsWith(参考:https ://docs.oracle.com/javase/8/docs/api/java/lang/String.html#startsWith-java.lang.String- )

在您的情况下,用法应该看起来像这样:

if(SkillChoice.nextLine().toLowerCase().startsWith("str") {
    System.out.println("How many points towards Strength?");
    System.out.println("Your current Strength is " + Attribute.Strength);

    SkillChoice.nextDouble();

    Attribute.setStr(SkillChoice.nextDouble() + Attribute.getStr());
    System.out.println(Attribute.Strength);
}
else if(SkillChoice.nextLine().toLowerCase().startsWith("sta") {
// Your stamina stuff here
}

祝你好运和来自德国的问候

PS:我希望(特别是)Attribute不是真正的类名(大写的 A 表示它),因为这意味着该类中的所有方法都是静态的,因为否则您将需要该类的对象来调用它们。无论哪种方式,这都很糟糕,您应该专注于消除这些错误,因为随着您的项目变得越来越大,它们确实会使您和其他人无法阅读代码。


推荐阅读