tauk

Generating random numbers and selection and string compariso

Jun 25th, 2020
1,147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class EvenOddQuiz {
  4.     public static void main(String args[]) {
  5.        
  6.         int rights = 0;
  7.         int wrongs = 0;
  8.            
  9.             //create Scanner for user input
  10.             Scanner scanner = new Scanner(System.in);
  11.            
  12.             for (int i = 1; i <=7; i++) {
  13.                 //generate a number between 1 and 20 and cast it to int
  14.                 int randInt = (int) (1 + Math.random() * 20);
  15.                
  16.                 //show this randInt to the user
  17.                 System.out.print("Is " + randInt + " odd or even?");
  18.                 //get the response from the user
  19.                 String userAnswer = scanner.next();
  20.                
  21.                 //set the correct answer so even or odd
  22.                 String correctAnswer;
  23.                 if (randInt % 2 == 0) {
  24.                     correctAnswer = "even";
  25.                 }
  26.                 else {
  27.                     correctAnswer = "odd";
  28.                 }
  29.                
  30.                 //compare the user response to correct answer
  31.                 if (userAnswer.equals(correctAnswer)) {
  32.                     rights++;
  33.                 }
  34.                 else {
  35.                     wrongs++;
  36.                 }
  37.             }
  38.            
  39.             System.out.println("rights = " + rights);
  40.             System.out.println("wrongs = " + wrongs);
  41.         }
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment