Reputation: 37
This is probably a simple fix, but I am just not seeing it. I am trying to figure out, how do I get my printOut()
method to print properly from the main Project5PartA
? Do I need get, set, and return methods? Also, is my while loop even necessary in the Tester
class?
The program compiles and keeps running to infinity, so I guess the while loop is wrong. But it also only prints out [Ljava.lang.String;@7c1c8c58
continuously on each line.
The classes that extend the main are irrelevant and part of the project. Apologies if this was posted wrong and thanks for any help.
The output of the whole program would be similar to:
Bark, bark.
Meow, meow.
Roooaaar.
Dog says woof, woof.
Cat says meow, meow.
Tester Class:
public class Tester {
String[] animalArray = {"Dog", "Cat", "tRex", "Cow", "Pig", "Snake",
"Goat", "Owl", "Chicken", "Frog"};
String[] noiseArray = {"Woof, woof", "Meow, meow", "Roooaaar", "Mooo",
"Oink, oink", "Hissss", "Baaa", "Hoot, hoot", "Bock, bock",
"Ribbit, ribbit"};
String[] printArray = new String[10];
public String printOut() {
while (true) {
for (int i = 0; i < 10; i++) {
String value = (animalArray[i] + " says " + noiseArray[i] + ".");
printArray[i] = value;
System.out.println();
System.out.println(printArray);
break;
}
}
}
}
Upvotes: 1
Views: 478
Reputation: 8247
Use Arrays.toString()
to print the contents of an array. Don't actually print the array itself.
System.out.println(printArray); // Prints [Ljava.lang.String;@7c1c8c58
System.out.println(Arrays.toString(printArray0); // Prints [Dog says Woof, woof...]
If you do use Arrays.toString()
, print the array outside the loops.
You could also just print each part of the array with System.out.println(printArray[i])
inside the loop.
public String printOut() {
while (true) {
for (int i = 0; i < 10; i++) {
String value = (animalArray[i] + " says " + noiseArray[i] + ".");
printArray[i] = value;
System.out.println();
System.out.println(printArray[i]); // This works
break;
}
}
System.out.println(Arrays.toString(printArray); // Also works
}
Upvotes: 2
Reputation: 2036
You don't need the while loop unless you really want your program to run forever.
You should change your print statement as follows. (You were printing the array object, not the array contents.)
System.out.println(printArray[i]);
Upvotes: 1
Reputation: 750
Because printArray is array and doesn't have a toString() method you will have to print out each element seperatly or use Arrays.toString(printArray) method.
Something like this will get you a growing array if it's in the while loop. Place it outside the while loop:
System.out.println(Arrays.toString(printArray));
Or in the while loop:
System.out.println(printArray[i]);
Upvotes: 1