简体   繁体   中英

I'm unable to assign values to array index. I have to assign values to individual variables

I have two classes, The variable (name1_i) in class Child (name of my second class) prints null value yet I'm expecting it to print "Tom" as assigned.

class parent{
    String name1="Tom",name2="John",name3="Harry";
    child pere = new child();
    public static void main(String[] args)throws Exception{
        child.introduce();
    }
}
class child{
    public static String name1_i,name2_i,name3_i;
    public static void introduce(){
        parent variable = new parent();
        String[] names_i = {name1_i,name2_i,name3_i};
        String[] names = {variable.name1 , variable.name2 , variable.name3 };
        System.out.println("");
        System.out.println("");
        //names_i[0] = name1_i = names[0];
        names_i[0] = names[0];
        //name1_i = names_i[0];
        System.out.println(names_i[0]);
        System.out.println(name1_i + "  <-- Expecting Tom");
    }
}

When I directly assign values to variables ie name1_i = "Tom"; (comment line 18) - it returns the expected value.

Your logic works fine. The problem is that you have many syntax error in your code. Try to use the following and it will work:

public class Parent {

   public String name1="Tom",name2="John",name3="Harry";
    
    public static void main(String[] args)throws Exception{
        Child pere = new Child();
        pere.introduce();
    }
    
}

class Child{
    public static String name1_i,name2_i,name3_i;
    public static void introduce(){
        Parent variable = new Parent();
        String[] names_i = {name1_i,name2_i,name3_i};
        String[] names = {variable.name1 , variable.name2 , variable.name3 };
        System.out.println("");
        System.out.println("");
        //names_i[0] = name1_i = names[0];
        names_i[0] = names[0];
        //name1_i = names_i[0];
        System.out.println(names_i[0]);
        System.out.println(name1_i + "  <-- Expecting Tom");
    }
}

Once you become more familiar with Java (syntax, packaging and other basic aspect of the language) then try to get a good book on Object Oriented (OO) programming. At the moment your code doesn't comply with the OO standards.

You are assigning empty string variables to the array names_i then you are replacing the index 0 at array names_i with the value at index 0 of the array names.

If you need to keep your current implementation, you need to assign values to static String variables in the class child before adding them to the array and don't replace the values at array names_i with values from names array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM