Gr-9 - Ch-3 - Loops with Java - Questions
Gr-9 - Ch-3 - Loops with Java - Questions
Chapter-3
Q2). Define the while loop and explain it using its syntax?
Q4). What is for loop? Explain for loop using its syntax?
Q8). Write a program to print first 10 natural numbers using a while loop.
Q10). Write a program to print first 10 natural numbers using a for loop.
3). Create a Rock, Paper, Scissors game in Java where one player will be the computer and
the other player is the user.
Ans).
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[ ] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
String[ ] choices = {"Rock", "Paper", "Scissors"};
System.out.println("Welcome to Rock, Paper, Scissors game!");
while (true) {
System.out.print("Enter your choice (Rock, Paper, Scissors) or 'exit' to end the game: ");
String userChoice = scanner.nextLine().toLowerCase();
if (userChoice.equals("exit")) {
System.out.println("Game ended. Goodbye!");
break;
}
if (!userChoice.equals("rock") && !userChoice.equals("paper") &&
!userChoice.equals("scissors")) {
System.out.println("Invalid choice. Please enter Rock, Paper, or Scissors.");
continue;
}
int computerIndex = random.nextInt(3);
String computerChoice = choices[computerIndex];
System.out.println("Computer chose: " + computerChoice);
determineWinner(userChoice, computerChoice);
}
scanner.close();
}
public static void determineWinner(String userChoice, String computerChoice)
{
if (userChoice.equals(computerChoice)) {
System.out.println("It's a tie!");
} else if ((userChoice.equals("rock") && computerChoice.equals("scissors")) ||
(userChoice.equals("paper") && computerChoice.equals("rock")) ||
(userChoice.equals("scissors") && computerChoice.equals("paper"))) {
System.out.println("You win!");
} else {
System.out.println("Computer wins!");
} } }