-6

I get this syntax when i'm trying to print each element in my tab : why? thanks

public class Solo {
public int val;

public Solo(int val){
    this.val=val;
}


public static void print(Solo[] tab){
    for (Solo s : tab) {
        System.out.println(s);
    }


Solo s1 = new Solo (1);
    Solo s2 = new Solo (2);
    Solo s3 = new Solo (3);
    Solo s4 = new Solo (4);

    Solo[] tab = {s1,s2,s3,s4}; 
    print(tab);

Output:

cours4.Solo@15db9742
cours4.Solo@6d06d69c
cours4.Solo@7852e922
cours4.Solo@4e25154f
pycarrre
  • 95
  • 2
  • 6
  • 3
    *What* syntax error? You've given output, which means there isn't a syntax error, because it must have compiled... – Jon Skeet Jan 10 '15 at 12:13
  • 2
    You need to implement the `toString()` method in your class `Solo` –  Jan 10 '15 at 12:13
  • 1
    If you mean "my output isn't as I expected it to be" you should specify what you expected and why. That's not the same as a syntax error. I strongly suspect you really just want to override `to`String()` but you should work on making your question clearer. – Jon Skeet Jan 10 '15 at 12:14

5 Answers5

0

cours4.Solo@15db9742 cours4.Solo@6d06d69c cours4.Solo@7852e922 cours4.Solo@4e25154f

are your instanciated objects , do this to print your object attributes :

public static void print(Solo[] tab){
    for (Solo s : tab) {
        System.out.println(s.val);
    }
Jileni Bouguima
  • 444
  • 2
  • 6
0

these are all the objects not variables. You should print the variables

so use

 System.out.println(s.val);
Karthikeyan
  • 1,119
  • 1
  • 15
  • 33
0

You have created Solo objects and added them to Array of type Solo and then printing the Array object. Fundamentally you are doing wrong. If you want to print the object then either you have to call toString () of Object class or override the toString () method inside your class Solo as below. I am sure it will work.

    public String toString() {
        return val+"";
    }
0

You are trying to print Objects. s1, s2, s3 and s4 are objects. If you try to print an Object, it will print the reference (address) of that Object. That is not a syntax error.

If you want to print the values from the object, You should override the toString() method in the Solo class.

public String toString() {
    return "Value:" + val;
}

Then it will print:

Value:0
Value:0
Value:0
Value:0

Because you didn't initialise the object with values. However, you have called the default constructor when creating the objects, and the default value for int fields is 0.

bcsb1001
  • 2,834
  • 3
  • 24
  • 35
Suganya Karthik
  • 131
  • 1
  • 1
  • 9
-1

s1,s2,s3 and s4 are objects that is why it is printing the address of the object, to print the value you need to access the variable

Pranav Agrawal
  • 466
  • 6
  • 17