【发布时间】:2016-08-20 20:34:10
【问题描述】:
public class RunProg {
static int input1; //for creating new human;
static boolean Married; //for knowing if married or not
static String isMarried; //for the YES or No of Married Boolean
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("What would you like to do? \n 1-Create new Human?\n");
input1 = input.nextInt();
input.nextLine();
//Inputs for The NEW HUMAN
if (input1 == 1) {
System.out.println("Enter name:");
String Name = input.nextLine();
System.out.println("Good! Now enter the age of " + Name + ": ");
int Age = input.nextInt();
System.out.println("Well done! Now enter length: ");
int Length = input.nextInt();
input.nextLine();
System.out.println("Finally, is he/she married? ('YES' or 'NO') ");
isMarried = input.nextLine();
if (isMarried == "YES") {
Married = true;
Human h1 = new Human(Name, Age, Length, Married);
}
else if (isMarried == "NO") {
Married = false;
Human h1 = new Human(Name, Age, Length);
}
}
如何修改此代码以使 h1 在 if-else 内部和外部都可访问
没有在 if-else 之外声明它?
这是解决对象的可访问性问题,该可访问性严格限定在 if-else 语句的括号之间
我在问是否有办法让括号外的“内部”可访问(我完全理解变量的范围;所以请不要用范围、命名约定和外部声明来打扰我)
【问题讨论】:
-
把它移到外面。它的范围仅限于
if的{}。 -
好吧,他的问题是如何在不将其移到外面的情况下做到这一点,我认为这是不可能的
-
没错。您可以在外部声明它但在内部实例化,但您无法解决范围问题。
-
这也会破坏您的代码:if (isMarried == "YES") {
-
您听说过命名约定(如 JCC)吗?静态变量也不是一个好的选择
标签: java class object if-statement