简体   繁体   中英

Why does my toString method return 0?

Why does my toString method return 0? I have to concatenate an randomly generated integer onto a String and when I print the result it is always 0. What should I do?

class Cozi:

public String toString(){
    String concat="";
    Clienti ob = new Clienti();
    for(int i=1;i <= Clienti.getNrClienti();i++){
        concat = " <" + ob.getRandomInt2() + ">";
        System.out.print(concat);
    }       
    return concat;
}

class Clienti:

public int serviceTime(){
    System.out.print("\n");
    Random randomServ = new Random();
    for (int idx = 1; idx <= nrClienti; ++idx){
        randomInt2 = randomServ.nextInt(maxServ);
        System.out.println("Generated : " + randomInt2);
    }
    return randomInt2;  
}

I have also the methods get and set randomInt2.

I foud out why I was getting only 0. Because randomInt2 was declared int in class Clienti, instead of private static int. Now the problem I got is that my concat object gets only the last value for randomInt2. Any suggestions?

If you have an empty String "" as a return value, then it means you do not enter the for loop. Check if the condition i <= Clienti.getNrClienti() is met for any i .

And there is a bug in the for loop, you have to modify:

    concat=" <"+ob.getRandomInt2()+">";

By

    concat += " <"+ob.getRandomInt2()+">";

Note: when you want to concatenate String s you can use StringBuilder which is more performant.

String s = "a";
s = "b";
System.out.println(s); // b

You want to concat if I got that right:

String s = "a";
s = s + "b";
System.out.println(s); // ab

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