Loop Repeat?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kamaria
    New Member
    • Feb 2009
    • 8

    Loop Repeat?

    I'm writing a program where it asks a user a number between a range and then displays $ the number of times of the number entered.

    But I'm needing to have this repeat 5 times (or more if an invalid number is entered).


    EDIT:::: Got the repeat fixed, just needing to have it repeat if it goes to the else statement.


    Here is my code so far.

    Code:
    import java.util.Scanner;
    public class Lab7_Ex1
    {
    	public static void  main(String[] args)
    	{
    		
    		Scanner keyboard = new Scanner(System.in);
    		int x;
    		int count=1;
    		
    		for (count = 5; count<=5; count++)
    		{
    			System.out.print("Enter an integer in the range 1-10: ");
    			x = keyboard.nextInt();
    		
    			if ( x >= 1 && x <= 10)
    				{ 	
    					for (int i = 1; x<=1; i++);
    					{
    						for (int j = 1; j <= x; j++)
    						{
                              System.out.print('$');
                      }
                      System.out.println();
                   }
    				}
    			else
    				{
    					System.out.println("Invalid number");
    				}
    			}
    		}
    	}
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    I didn't read your code but my eye was attracted to this line:

    Code:
          
    for (count = 5; count<=5; count++)
    You probably intended to write:

    Code:
          
    for (count= 0; count < 5; count++)
    kind regards,

    Jos

    Comment

    • Kamaria
      New Member
      • Feb 2009
      • 8

      #3
      Thanks that helped but how do I make it repeat if the number is invalid?

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by Kamaria
        Thanks that helped but how do I make it repeat if the number is invalid?
        Don't increment the loop counter if the number is not valid; something like this:

        Code:
        for (int count= 0; count < 5; ) { // <-- see? no increment
           // obtain a number
           if (isValid()) {
              // do some work
              count++; // increment counter
           }
           else {
              // do some other work and don't increment
           }
        }
        kind regards,

        Jos

        Comment

        Working...