Reputation: 111
I am attempting to represent an int
as a String
using the toString()
method and I am not exactly sure how to achieve the desired results.
what I have is:
public class Item {
int item;
public Item () {
item = 3;
}
public Item (int item) {
this.item = item;
}
public void toString() {
String[] anArray = new string[10];
anArray[0] = "item 0";
anArray[1] = "item1";
anArray[2] = "item2";
anArray[3] = "item3";
anArray[4] = "item4";
anArray[5] = "item5";
anArray[6] = "item6";
anArray[7] = "item7";
anArray[8] = "item8";
anArray[9] = "item9";
if (item >= 0 && item < 10)
System.out.println("Item " + item + " = " + anArray[item]);
else
System.out.println("Item does not exist.");
}
}
How can I represent an int
as a String
in an array?
Upvotes: 1
Views: 117
Reputation: 4972
int to String:
int a=9;
String b = Integer.toString(a);
and
String to int:
String a="9";
int b=Integer.parseInt(a);
Upvotes: 0
Reputation: 15533
It is not clear exactly what is your desired result, but if you want to have a toString
method that returns "item1" when item
is 1, "item2" when item
is 2, and so forth, you should bear in mind:
toString()
should return a String
.item
.This would be:
public String toString() {
return "item" + item;
}
Upvotes: 2
Reputation: 328724
You probably want this:
public String toString() {
return "Item " + item;
}
The idea of the toString()
method is that it returns a simple but meaningful representation of the instance.
Usually, you should include the name of the class (you can use getClass().getSimpleName()
or a string) plus a few key fields.
Upvotes: 3