Click here to Skip to main content
15,615,280 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys,

In an exercise on toString() methods in Java, our teacher asks us to write the following method without using StringBuilder : 

public String toString() {
		StringBuilder concatchar = new StringBuilder();
		if (value >= 2 && (value <= 10){
		}else if (value == 11){
		}else if (value == 12){
		}else if (value == 13){
		}else if (value == 14){
		concatchar.append(" of ");
		return concatchar.toString();

I know I have a problem with the type of my data. But I don't know how to get out of it. In addition, I have to manage several values for 11, 12, 13 and 14. 

Thanks ;-)

What I have tried:

<pre>I tried with the "+" operator and the concat() method but without success. Is it possible with "+" or concat() please ? If I try with <pre><pre lang="Java">value + " of " + color.toString()
I know I'm not writing the method correctly, but I'm completely stumped on it because I was only using "+" or the concat() method before.
Updated 13-Dec-21 10:05am

1 solution

"+" and concat() ARE alternatives to StringBuilder (SB); though SB is usually the preferred method as the number of appends increases.

The thing to remember is if you start concatenating "numbers" (via +) instead of "strings", you get arithmetic "addition"; not concatenation; so, concatenate the "string value of value", and not just "value" when using "+".
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900