Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

java - 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 i.e name1_i = "Tom"; (comment line 18) - it returns the expected value.

question from:https://stackoverflow.com/questions/65873540/im-unable-to-assign-values-to-array-index-i-have-to-assign-values-to-individua

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...