java允许用户输入同名变量
我目前正在使用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****”,其中*是任何字符串组合,并且程序应该将其识别为想要增加力量或耐力点
# 1 楼答案
我认为你应该摆脱整个开关/案例代码,坚持使用if子句。这是因为我在下面解释的东西,它不适用于开关/case,如果你真的想坚持使用它,你至少应该查找正确的语法,因为你缺少任何中断
这样,您就可以简单地使用字符串类(Ref:https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#startsWith-java.lang.String-)的方法startsWith
在您的情况下,用法应该有点像这样:
祝你好运;来自德国的问候
PS:我希望(尤其是)属性不是真正的类名(大写字母a表示),因为这意味着该类中的所有方法都是静态的,因为其他原因需要类的对象来调用它们。不管怎样,这都是不好的,你应该集中精力消除这些错误,因为随着你的项目越来越大,它们真的会让你和其他人看不懂代码