Kathirvel Appusamy Kathirvel Appusamy - 3 months ago 17
Java Question

How to append single quotes into both side of stringBuilder object in java

I would like to add single quotes into an array of string. If I has 5 values.(1,2,3,4,5). I need like this '1','2','3','4','5'

I have tried some like below but I am getting error

public class Main()
{
StringBuilder values=new StringBuilder();

values=getValues(1);

System.out.println(values.toString());

public StringBuilder getValues(int productid){
StringBuilder Variable_1=new StringBuilder();
Variable_1=get(productid);
return Variable_1.deleteCharAt(Variable_1.length()-1);
}

public static StringBuilder get(String product)
{
/Some quoatoes to retrive value from db/
while (rs.next()) {
number = rs.getString("org");
orgNames.append("'");
orgNames.append(number);
orgNames.append("'");
orgNames.append(",");

}
return orgNames;
}
}


I am getting exception as follow

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:766)
at java.lang.StringBuilder.deleteCharAt(StringBuilder.java:280)
at calc.getValues(process.java:8)

Answer

in the last iteration Variable_1.length()-1 returns index out of bound because Variable_1.length() is zero.

Check

if(Variable_1.length()>0)

before deleteCharAt