Problem with array in Java. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Problem with array in Java.

Hi, I have small problem with this code, in a second array it returns me place in memory instead of result ( I mean it should return 1 and 2 like in alphabet method a and b).

16th Sep 2017, 7:58 AM
MatL
MatL - avatar
2 Answers
+ 3
public class Chair { public static void main(String[] args) { Chair chair = new Chair(); System.out.println(chair); Tree tree = new Tree(); System.out.println(tree); System.out.println(new Tree()); //System.out.println(Tree.numbers()); // This won't work numbers() returns an array } public static char[] alphabet() { // this needs to be a char array not a String array return new char[] {'a', 'b'}; } @Override public String toString() { return String.valueOf(alphabet()); } static class Tree { static int[] numbers() { return new int[] {1,2}; } @Override public String toString() { String s = ""; for(int i: numbers()) { s += String.valueOf(i); // int arrays don't work the same way as a char array will with valueOf. instead you need to loop over each int within the array. } return s; } } } Review the overloaded versions of the method and what the different possible parameters can be. https://www.javatpoint.com/java-string-valueof
16th Sep 2017, 8:27 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Public class Chair{ Public static void main(String[]args){ Chair chair = new Chair(); System.out.println(chair); Tree tree = new Tree(); System.out.println(tree); System.out.println(new Tree()); System.out.println(Tree.numbers()); } public static String[] alphabet(){ return new String[] {"a", "b"}; } @Override public string toString(){ return String.valueOf( alphabet())}; static class Tree{ static int[] numbers(){ return new int[] {1,2}; } @Override public string toString(){ return String.valueOf( numbers()) } } } Why it does not works in case in array numbers?
16th Sep 2017, 7:59 AM
MatL
MatL - avatar