Storing a string in a created obj type

  • Thread starter Thread starter kolleamm
  • Start date Start date
  • Tags Tags
    String Type
AI Thread Summary
To store a string in an array of a custom object type in Java, the object type must be compatible with the string, as demonstrated with Object arrays. The user attempted to assign a string directly to an array of a custom type but encountered issues. A successful example was provided using an Object array, where a string was stored without problems. However, casting a string to a Float type failed, highlighting type compatibility issues in Java. The discussion clarifies that the language in question is Java, emphasizing the importance of type matching when storing values in arrays.
kolleamm
Messages
476
Reaction score
44

Homework Statement


How can I store String s in X x_obj [] = new X [100] ;2. What I tried
I tried

x_obj [0] = s;
But it didn't work. I know there are easier ways but this is how I have to do it.

Thanks in advance
 
Physics news on Phys.org
If X is Object then it should work. I tried it in a processing sketch and it worked okay:

Java:
void setup() {
   Object[] x = new Object[100];
   String s = "hello";
   x[0]=s;      // Object is the parent class to all java classes
   println("x[0]="+x[0]);
}

whereas attempting to cast the string to a FLoat class doesn't work:

Java:
void setup() {
   Float[] x = new Float[100];
   String s = "hello";
   x[0]=(Float)s;       // fails with can't cast String to Float
   println("x[0]="+x[0]);
}
 
How did you guess the language ? I thought better of asking OP for it since that would have thrown the thread off the unanswered list...
 
BvU said:
How did you guess the language ? I thought better of asking OP for it since that would have thrown the thread off the unanswered list...
The language is Java, apologies I completely forgot to mention it
 

Similar threads

Replies
2
Views
2K
Replies
12
Views
2K
Replies
10
Views
2K
Replies
1
Views
2K
Replies
8
Views
1K
Replies
2
Views
2K
Replies
1
Views
1K
Replies
10
Views
3K
Back
Top