So my program is supposed to iterate over a list of numbers (0-113) and then print the numbers line by line. If the number is odd, that should be added next to the number, if the number is divisible by 5, that should be added next to the number and so on. So I have my 4 boolean methods done and they look like this:
public static boolean isDivisibleBy5(int n){
if (n%5 ==0){
return true;
}
return false ;
}
Next I have a method that I am required to use as per assignment requirements and it is as follows:
public static ArrayList<String>iterate()
So the definition with this method is where I am having problems. Right now what I have is this:
public static ArrayList<String>iterate(){
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<114;i++){
if (isOdd(i)){
list.add(i+" Is odd");
}
if(isDivisibleBy5(i)){
list.add(i+" hi five");
}
if(isDivisbleBy7(i)){
list.add(i+" wow");
}
if (isPrime(i)){
list.add(i+" prime");
}
}
for(String elem:list)
System.out.println(elem);
return list;
}
But unfortunately my output looks like this:
0 hi five
1 Is odd
1 prime
3 Is odd
3 wow
3 prime
5 Is odd
5 hi five
5 prime
7 Is odd
7 prime
9 Is odd
10 hi five
10 wow
11 Is odd
I need it to look like this:
0, hi five
1, Is Odd, prime
2
3, Is odd, wow, prime
4
5, Is Odd, hi five, prime
etc.
So my question is basically how do I get all the conditions (when true) to add themselves to the same line with the corresponding number and also have the numbers that don't meet the conditions print on their lines as well, like 2 and 4 and 6. I've been stuck on this question for awhile and I feel like there is a crucial piece of java that I am not thinking of that is required here. String Builder maybe? I'm not sure. Any help is appreciated. Even if you can just point me to a concept to look up and learn more of.
Thanks
EDIT: I am seeing a lot of responses about building the string first and then adding to it. I believe this was the concept that I was not thinking of that has held me back so I will read up and practice implementing that. Thanks again for the quick responses. When I get it working I will come back here and up-vote anyone who helped.
Stringand THEN adding it to the list?String conditions = ""; if (isOdd()) conditions += ", is odd": if (isPrime) conditions += ", is prime": list.add(i + "conditions);