| Author |
Why this program stops the execution in middle?
|
saikrishna cinux
Ranch Hand
Joined: Apr 16, 2005
Posts: 689
|
|
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
|
A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
SCJP 1.4
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
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 ]
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24039
|
|
|
Let's continue this conversation in "Java in General (Beginner)."
|
[Jess in Action][AskingGoodQuestions]
|
 |
saikrishna cinux
Ranch Hand
Joined: Apr 16, 2005
Posts: 689
|
|
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
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
|
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?
|
 |
 |
|
|
subject: Why this program stops the execution in middle?
|
|
|