简体   繁体   中英

My test method is returning null when I run it

Apologies if the answer to this question is obvious! I've tried to initialize my field numbers with an array of numbers in a constructor in one class and then call it in my test class and display it as a string but it keeps returning null ....any help would be appreciated!

This is my class that has the constructor:

public class NumerbList implements Number {
    ArrayList<Number> numbers = new ArrayList<Number>();

    //constructor taking array of type double as parameter
    public NumberList(Double[] numberlist){
        for(int i=0; i<numbers.size(); i++){
            NumberDouble numberd = new NumberDouble(numberlist[i]);
            numbers.add(numberd);
        }
    }

and the test class that creates an object of the NumberList class

public class Test {
    public static void main(String[]args){
        Double[] d = {2.4, 3.6, 4.3, 5.1};
        NumberList numbers = new NumberList(d);
        numbers.neg();

        System.out.print(numbers.asString());
    }
}

sorry neg is as follows :

public void neg(){
    for(int i=0; i < numbers.size(); i++){
            numbers.get(i).neg();
    }
}

and asString is :

@Override
public String asString(){
    return numbers.toString();
}

Should I put

     for(int i=0; i < numberlist.length(); i++;) 

in neg? Thanks in advance!

The problem is that your for loop is using your initialize empty ArrayList as the size.

Change your loop to this:

for (int i = 0; i < numberlist.length; i++) {
    // your loop logic here
}

Hope that helps!

for(int i=0; i<numbers.size(); i++){应该是for(int i=0; i<numberList.length; i++){

Also note that there is an easier (and generally preferred) way to iterate over your array:

for (Double number : numberlist) {
    // your loop logic here
}

(I'd post that as a comment but it would lose the code formatting).

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