有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

类Java IfElse不可访问insideobject声明

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语句的括号之间 我在问是否有一种方法可以在括号外访问“inside”(我完全理解变量的作用域;所以请不要用作用域、命名约定和外部声明来打扰我)


共 (2) 个答案

  1. # 1 楼答案

    如果有人阻止呢

    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();
    
            Human h1 = new Human(Name, Age, Length, "YES".equals(isMarried));
        }
    }
    
  2. # 2 楼答案

    您必须将h1声明移动到外部范围才能在那里访问它。变量是块范围的。然后在if块中初始化变量

    if (input1 == 1) {
        Human h1;
        ...     
    
        if ("YES".equals(isMarried)) {
            Married = true;
            h1 = new Human(Name, Age, Length, Married);
        }
    
         else if ("NO".equals(isMarried)) {
            Married = false;
            h1 = new Human(Name, Age, Length);
        }
    
    }
    

    或重构以删除If/Else块:

    Human h1 = new Human(Name, Age, Length, "YES".equals(isMarried));
    

    编辑:切换到呼叫。等于“是”,因为它不会为空