Java Lab 6 – For Loops and input
Create a new Java file (empty Java file), save it to your H: drive, call it lab6
Insert the following code to set up your program:
import java.util.Scanner;
import java.util.Random;
public class lab6 {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
Random rand = new Random();
100pt:
Use random numbers to create a math game. The program will ask the user 5 addition questions, with
two random numbers between 1 and 999. The user will answer each question, and tell them if they got
the answer correct or not.
The program must have the following features:
- Uses a for loop to ask the 5 questions
- Generates new random numbers for each question
- Shows the user whether or not they got the answer right after each question
- Keeps track of how many questions out of 5 they got correct.
-
Notes:
A loop that runs between 0 and 4:
for(int i = 0; i < 5; i++){
System.out.println(i);
To generate a random number between 0 and 100:
int x = rand.nextInt(100);
To “concatenate” strings
String a = “hello”;
String b = “world”;
System.out.println(a + b);
To include a space:
System.out.println(a + “ “ + b);
To concatenate integers into Strings:
System.out.println(15 + “ + “ + 20); // Outputs “15 + 20”