在下面; 我正在尝试打印用户输入的一些信息。我相信我有一个范围问题。当用户选择A时;他们能够制作一个新角色,然后打印他们的名字。如果他们然后按 V;它失败了,但有一个例外。
java.lang.RuntimeException:无法编译的源代码 - 变量 newChar 可能尚未初始化
如果他们添加了新角色;为什么程序不允许我在选项 V 中打印 getFirstName 但它在选项 A 中这样做?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package rpgmanager;
import java.util.Scanner;
/**
*
* @author Aaron
*/
public class RpgManager {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Set Run Boolean to true
boolean running = true;
// "Splash Screen here"
System.out.println("Welcome to character generator.");
// If the program is running; offer the user options
while(running) {
System.out.println("A: New Char ; V: View ; S: Save ; D: Delete ; Q: Quit");
// Initialize the scanner
Scanner user_input = new Scanner(System.in);
// Prepare to accept a string
String decision;
// Get the user input
decision = user_input.next();
// We switch the input to lowecase here and compare
switch (decision.toLowerCase()) {
case "a":
Character newChar = new Character();
System.out.println(newChar.getFirstName());
break;
case "s":
break;
case "d":
break;
case "v":
try {
System.out.println(newChar.getFirstName());
} catch(Exception e) {
System.out.println("You have an exception - ");
System.out.println(e);
}
break;
case "q": System.exit(0); // Kill the program
break;
default: System.out.println("You did not select a viable option.");
System.out.println("Try again.");
break;
}
}
}
}
/*
*
*
*/
package rpgmanager;
import java.util.Scanner;
/**
*
* @author Aaron
*/
public class Character {
private String First_Name;
private String Last_Name;
private String Height;
private int Weight;
private int Age;
public Character() {
System.out.println("Creating new character...");
Scanner user_input = new Scanner(System.in);
System.out.println("What is your first name?");
First_Name = user_input.next();
System.out.println("What is your last name?");
Last_Name = user_input.next();
System.out.println("What is your height?");
Height = user_input.next();
System.out.println("What is your weight?");
Weight = user_input.nextInt();
System.out.println("What is your age?");
Age = user_input.nextInt();
}
/**
*
*/
public String getFirstName() {
return First_Name;
}
public String getLastName() {
return Last_Name;
}
}