Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this program stops the execution in middle?

 
saikrishna cinux
Ranch Hand
Posts: 689
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to run this programs but at line XXX it stops the flow.
why it happens if i use name=name.toUpperCase();?




import java.util.*;
public class PinGen{
public static void main(String args[])

{


Random r=new Random();
long i=r.nextLong();

String number=new String();
number=number.valueOf(i);


number=number.substring(1,5);
System.out.println(number);




String name="abcdefghijklmnopqrstuvwxyz";

int nameLength=name.length();

line XXX:name=name.toUpperCase();

StringBuffer sb=new StringBuffer(number);
int l=0;
while(l<4)
{
int randomChar=(int)(Math.random()*nameLength);

//System.out.println(randomChar);
char c=name.charAt(randomChar);
//System.out.println(c);
sb.insert(l+1,c);

}

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



}
}



cinux
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It does not stop executing in the line you marked with "XXX". Look at the loop just below.

The loop runs as long as l is less than 4. Inside the loop, you are not changing the value of l anywhere. So l always stays at 0, and the loop is running forever (or until an OutOfMemoryError occurs, but that may take a long time).
[ December 01, 2005: Message edited by: Jesper de Jong ]
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's continue this conversation in "Java in General (Beginner)."
 
saikrishna cinux
Ranch Hand
Posts: 689
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya, you r right i havn't checked it clearly.
i was in hurry....
so can u please tell me that the code which i have given

int l=0;
while(l<4)
{
int randomChar=(int)(Math.random()*nameLength);

//System.out.println(randomChar);
char c=name.charAt(randomChar);
//System.out.println(c);
sb.insert(l+1,c);

}


is this same as the below code

while(true)
{
int randomChar=(int)(Math.random()*nameLength);

//System.out.println(randomChar);
char c=name.charAt(randomChar);
//System.out.println(c);
sb.insert(l+1,c);

}


I mean both loops lead to infinity



:roll:


cinux
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's very easy to see, if you think about it just a little bit, that the second loop does exactly the same as the first loop. Is that all you wanted to know?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic