break for loop help?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • JanineXD
    New Member
    • Feb 2010
    • 18

    break for loop help?

    I have this program:
    Code:
    import java.io.*;
    
    public class AnyFibonacci{
    	public static void main(String[]args)throws IOException{
    		BufferedReader In = new BufferedReader(new InputStreamReader(System.in));
    		
    		for(;;){
    		
    			System.out.println("Input Test Case <Iterations StartVal_1 StartVal_2> ");
    			String l = In.readLine();
    			
    			String con[] = l.split("\\s+");
    			
    			int inc = Integer.parseInt(con[0]);
    			int s1 = Integer.parseInt(con[1]);
    			int s2 = Integer.parseInt(con[2]);
    			int total = 0;
    			
    			if((inc<2 || inc>100) || !(s1>1 || s1<100) || !(s2>1 || s2<100) ){
    				System.out.println("Invalid Length");
    				continue;
    			}
    			
    			if(s1>s2){
    				System.out.println("Second number should be greater than the first");
    				continue;
    			}
    			System.out.print(s1+ " " + s2);
    			for(int x =0;x<inc-2;x++){
    				total = s1+s2;
    				System.out.print(" " + total);
    				s1 = s2;
    				s2 = total;
    			}
    			
    			System.out.println();
    			
    			
    			
    		}
    }
    }
    but when it outputs:
    Input Test Case <Iterations StartVal_1 StartVal_2>
    1 3 7
    Invalid Length
    Input Test Case <Iterations StartVal_1 StartVal_2>
    15 3 7
    3 7 10 17 27 44 71 115 186 301 487 788 1275 2063 3338
    Input Test Case <Iterations StartVal_1 StartVal_2>
    1 3 7
    Invalid Length
    Input Test Case <Iterations StartVal_1 StartVal_2>
    15 3 7
    3 7 10 17 27 44 71 115 186 301 487 788 1275 2063 3338
    Input Test Case <Iterations StartVal_1 StartVal_2>
    how can I make it end when the result is already shown?

    thanks!
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Your for loop will make it go on forever.
    for(;;)
    easiest change to your code is to have a break; at the end of the loop.

    In addition, consider moving the closing brace to before the output statement.

    Comment

    • JanineXD
      New Member
      • Feb 2010
      • 18

      #3
      thank you!

      I added break; after the system.out.prin tln();

      Comment

      Working...