我正在做一些Java只是为了练习,并决定做一个Dungeons&龙类型代码。 (这只是角色统计数据)
我输入了所有内容,它一直说(角色)最伟大的数据是生命力。帮助
import java.util.Random;
import java.util.Scanner;
public class DAndD {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Choose a name for your Dungeons & Dragons character.");
String character = input.next();
System.out.print("Ah, " + character + " has a nice ring to it.\nLet's roll for stats shall we?");
int str = generator.nextInt(21);
int dex = generator.nextInt(21);
int intel = generator.nextInt(21);
int wis = generator.nextInt(21);
int vit = generator.nextInt(21);
if (str > 0);
String trait = "strength";
int large = str;
if (dex > large);
trait = "dexterity";
large = dex;
if (intel > large);
trait = "intelligence";
large = intel;
if (wis > large);
trait = "wisdom";
large = wis;
if (vit > large);
trait = "vitality";
large = vit;
if(large == str){
System.out.println("\n" + character + "'s best stat is its strength!");
}
else if (large == dex){
System.out.println("\n" + character + "'s best stat is its dexterity!");
}
else if (large == intel){
System.out.println("\n" + character + "'s best stat is its intelligence!");
}
else if (large == wis){
System.out.println("\n" + character + "'s best stat is its wisdom!");
}
else if (large == vit){
System.out.println("\n" + character + "'s best stat is its vitality");
}
System.out.println("\nStrength: " + str + "\nDexterity:" + dex + "\nIntelligence: " + intel + "\nWisdom: " + wis + "\nVitality: " + vit);
}
}
所以,这就是现在的最终结果:
输出
Choose a name for your Dungeons & Dragons character.
*Toetar*
Ah, Toetar has a nice ring to it.
Let's roll for stats shall we?
Toetar's best stat is its vitality
Strength: 5
Dexterity: 19
Intelligence: 1
Wisdom: 6
Vitality: 4
答案 0 :(得分:5)
你的if语句(;
)后面有分号(if (vit > large);
),这些都是否定了它们的功能。这就是使用{...}
我"假设"你的意思是更像......
String trait = "";
int large = -1;
if (str > 0) {
trait = "strength";
large = str;
} else if (dex > large) {
trait = "dexterity";
large = dex;
} else if (intel > large) {
trait = "intelligence";
large = intel;
} else if (wis > large) {
trait = "wisdom";
large = wis;
} else if (vit > large) {
trait = "vitality";
large = vit;
}
答案 1 :(得分:1)
当if
中的条件表达式为if
时,true
之后的语句永远不会被评估,因为您在semi-colon
之后保留了if
不会认为你的下一个陈述是条件if
块的一部分:
例如:
if (str > 0); // you have kept ; semi-colon so it does nothing
String trait = "strength"; // this is independent of above statement
另外,正如@MadProgrammer在上面的回答中所建议的,如果你使用它:
if (str > 0) {
String trait = "strength";
int large = str;
}
您的变量trait
,large
只能在if
区块内访问。
首先在开始ifs
之前首先声明它们:
String trait = "";
int large = 0;
if (str > 0) {
trait = "strength";
large = str;
} else if (dex > large) {
trait = "dexterity";
large = dex;
}//and so on