If you want to do something a certain number of times, you use a for loop.
Example:
int i; for(i=0; i<10; i++){ System.out.println("This loop has executed " + (i+1) + " times."); } System.out.print("Execution has now jumped out of the loop and the current value of i is " + i + ".");
Practice tasks:
- Use a loop to print out all the numbers from 1 to 100 that are divisible by 7. (Extension: Allow the user to set the divisor and the number to go up to.)
- Use a loop to print out all the factors of a number supplied by the user.
If you want to loop as long as a condition is true, you use a while loop:
Example:
Scanner in = new Scanner(System.in); System.out.println("Please enter the secret code:"); int input = in.nextInt(); while (input != 1234){ System.out.println("Sorry. That is incorrect."); System.out.println("Please enter the secret code:"); input = in.nextInt(); } System.out.println("You have entered the correct code.");
Challenge: Change the above code so that it only allows three attempts to enter the correct code.
Practice Task:
Write a guessing game in Java in which the user has to guess a number between 1 and 100. The program should tell the user if they have guessed too high or too low and allow them to guess repeatedly until they are correct. (Extension: Look up how to use the Random object in Java so that your program chooses a different secret number each time.)