hi Guys, Here is a program using StringBuffer class.The problem i came across is : 1. When there is no space between the double quotes [StringBuffer str = new StringBuffer("");],the program throws an error java.lang.StringIndexOutOfBoundsException for "for loop2" after j=0. 2. When there is single space,then "for loo2" throws exception after j=1. 3. And when the space is more than 3,the program runs successfully. Can anybody plz throw a light on this. import java.util.*; public class ForLoop { Vector myStockSymbols; Vector myStockValues; private static char c[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; public ForLoop() { myStockSymbols = new Vector(); myStockValues = new Vector(); for(int i=0;i<10;i++) { System.out.println("for loop1 "+i); StringBuffer str = new StringBuffer(""); for(int j=0;j<4;j++) { System.out.println("for loop2 "+j); str.setCharAt(j,c[(int)(Math.random()*26f)]); } myStockSymbols.addElement(str.toString()); myStockValues.addElement(new Float(Math.random()*100f)); } for(int k=0;k<10;k++) { System.out.println("for loop3 "+k); System.out.println(" "+myStockSymbols.elementAt(k)+" "+myStockValues.elementAt(k)); } System.out.println("here"); } public static void main(String[] args) { ForLoop loop = new ForLoop(); } }
Thanks. shailendra
deekasha gunwant
Ranch Hand
Joined: May 06, 2000
Posts: 396
posted
0
Hi Shailendra, str.setCharAt(j,c[(int)(Math.random()*26f)]) in above line j is the index of the StringBuffer. and when there is no value in the StringBuffer (i.e. StringBuffer contains "").so the StringIndexOutOfBoundsException is thrown. again when StrinBuffer str = " " one space then loop tuns fine for index 0. but when it comes to index 1 then again there will be String...BoundsException. and since u r running your lop only 4 times i.e. only 0,1,2,3 indexes will be looked for so whenever the str has length >3 i.e. 4/5/6...... the loop will run properly
regards Deekasha
shailendra vasale
Ranch Hand
Joined: Dec 17, 2000
Posts: 38
posted
0
hi Deekasha, Thankx for ur reply.I got the point where i was confused. I tried the same using "StringBuffer str = new StringBuffer("abcd");",it works fine. shailendra.