1

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?

8
  • 2
    First of all, int is not a class. It's a primitive type. Commented Nov 13, 2013 at 15:08
  • 2
    What is your desired result? Commented Nov 13, 2013 at 15:09
  • I cannot figure what exactly do you want to achieve, I see no problems in your code. Commented Nov 13, 2013 at 15:09
  • int is not a class..its primitive type and second thing is that your question is not clear Commented Nov 13, 2013 at 15:09
  • String.valueOf(yourInt) converts your int to string. Commented Nov 13, 2013 at 15:15

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand how this is implemented. do I place arguments within this method? I'm just confused as to how it would actually work with the code that I have. ps..I'm a noob
Read up on "fields" and "arguments" and what an "instance" is.
2

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;
}

Comments

1

This might help you

String str = Integer.toString(x);

Comments

0

int to String:

int a=9;
String b = Integer.toString(a);

and

String to int:

String a="9";
int b=Integer.parseInt(a);

1 Comment

a is a primitive. Doesn't have any methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.