Java 允许使用相同名称的变量进行用户输入

Java 允许使用相同名称的变量进行用户输入,java,Java,我目前正在使用charAt(0)方法来允许用户进行输入。这是一个问题,因为我有一个以相同字符开头的变量。我想让程序读取本例中的前3个字符。换句话说,我如何确保我的程序在选择变量时识别正确的变量 另外,我知道我需要研究命名约定,我还是Java新手,正在学习 switch(SkillChoice.nextLine().toLowerCase().charAt(0)){ case 'd': System.out.println("How many points

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

另外,我知道我需要研究命名约定,我还是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****”,其中*是任何字符串组合,并且程序应该将其识别为想要增加力量或耐力点

我认为你应该去掉整个switch/case代码,坚持使用if子句。这是因为我在下面解释的东西不能用于switch/case,如果你真的想继续使用它,你至少应该查找正确的语法,因为你错过了任何中断

这样,您就可以简单地使用String类(Ref:)的startsWith方法

在您的情况下,用法应该如下所示:

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:我希望(特别是)属性不是真正的类名(大写字母a表示它),因为这意味着该类中的所有方法都是静态的,因为其他原因需要类的对象来调用它们。不管怎样,这都是不好的,你应该集中精力消除这些错误,因为随着你的项目越来越大,这些错误确实会使你和其他人无法阅读代码。

最初的案例应该是为了加强,第二个大小写“s”应该是为了耐力。您可能希望将字符保存在一个字符串中,该字符串由每个新字符组成,并使用
startWith()
查看是否有匹配项。如果有多个匹配项,则需要更多字符。如果只有一个匹配项,则知道要选择哪个属性。如果您根本没有匹配项,那么您输入了无法识别的内容。另一件事是,每个
案例
都不会以
中断
结束,这意味着代码执行将“失败”到下一个案例。这是一个严重的问题。例如,如果选择了
'd'
,则整个
开关
块中的所有语句都将执行,因为没有
中断
s。