我对一般编码以及这个网站都非常陌生,因此非常感谢您的帮助!
我编写的这段简短代码将不会运行,因为变量 str 不会初始化。 它看起来与按预期运行的其他几个变量相同。
我的问题是为什么会发生这种情况以及如何修复它。
这是代码
package firstgameattempt1;
import java.util.Scanner;
public class CreateChar {
public static void main (String Args[]){
System.out.println( "please enter your Characters name");
Scanner in = new Scanner (System.in);
String Cname = in.next();
System.out.println("so your name is ");
System.out.println(Cname);
System.out.println("thats the dumbest thing ive ever heard");
int str;
int intelligence;
int speed;
int hp;
int maxhp;
System.out.println("enter 1 if you are a warrior, 2 if you are a mage, or 3 if you are a thief ");
int Cclass = in.nextInt();
if (Cclass == 1 )
str = 10;
intelligence = 5;
speed = 7;
hp= 100;
maxhp = 100;
System.out.println ("your strength is");
//here is the problem
System.out.println (str);
//here is the problem
System.out.println ("your intelligence is");
System.out.println (intelligence);
System.out.println ("your speed is");
System.out.println (speed);
System.out.println ("you have ");
System.out.println (hp);
System.out.println ("hitpoints");
}
}
最佳答案
出现此问题的原因
int str;
创建时未初始化(如设置=0)。
您确实有代码将值设置为 10
但这仅当您的 if(Cclass==1)
的条件满足时才会发生声明是 true
,所以如果该语句是 false
, str
将保持未初始化状态。确保它始终具有值,无论是否 Cclass == 1
或不。
关于java - 尽管变量与其他有效的变量相同,但它并未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42726826/