user2988188
user2988188

Reputation: 111

How to represent an int as a string in an Array

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

Answers (4)

user2982937
user2982937

Reputation:

This might help you

String str = Integer.toString(x);

Upvotes: 1

Kamlesh Meghwal
Kamlesh Meghwal

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

Cyrille Ka
Cyrille Ka

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.
  • You don't need to construct an array, but just to return the concatenation of "item" and the value of item.

This would be:

public String toString() {
    return "item" + item;
}

Upvotes: 2

Aaron Digulla
Aaron Digulla

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

Related Questions