How can I apply an If ... Else in this program and how can I optimize this code, if possible?
You can just wrap your entire logic in a while loop and after the game is played, ask the user to play again or not. If he types yes, then you take him to the start else you just break out of the while loop.
import java.util.Random;
import java.util.Scanner;
public class DiceRoll {
public static void main(String args[]) {
int total = 0;
while (true) {
System.out.print("Enter the number of dice: ");
Scanner input = new Scanner(System.in);
int numberOfDice = input.nextInt();
// generating random numbers
Random ranNum = new Random();
System.out.print("You rolled: ");
int randomNumber = 0;
for (int i = 0; i < numberOfDice; i++) {
// Generating the random number and storing it in the 'randomNumber' variable
randomNumber = ranNum.nextInt(20) + 1;
total = total + randomNumber;
System.out.print(randomNumber);
System.out.println(" ");
}
System.out.print("");
System.out.println("Total: " + total);
System.out.println("do you want to play again- type yes or no ");
String s = input.next();
if (s.equalsIgnoreCase("yes")) {
continue;
} else {
input.close();
break;
}
}
}
// public static void main(String args[]) {
// int total = 0;
// do {
// System.out.print("Enter the number of dice: ");
// Scanner input = new Scanner(System.in);
// int numberOfDice = input.nextInt();
// // generating random numbers
// Random ranNum = new Random();
//
// System.out.print("You rolled: ");
//
// int randomNumber = 0;
//
// for (int i = 0; i < numberOfDice; i++) {
//
// // Generating the random number and storing it in the 'randomNumber' variable
// randomNumber = ranNum.nextInt(20) + 1;
// total = total + randomNumber;
// System.out.print(randomNumber);
// System.out.println(" ");
// }
//
// System.out.print("");
// System.out.println("Total: " + total);
// System.out.println("do you want to play again- type yes or no ");
// String s = input.next();
// if (s.equalsIgnoreCase("yes")) {
// continue;
// } else {
// input.close();
// break;
// }
// } while (true);
// }
}
Depending on whether you want to show the total for all the games ( then declare the total variable outside the while loop ) or you want to show the total for each game( then declare the total variable inside the for loop) The output comes in this format.
Enter the number of dice: 2
You rolled: 17
16
Total: 33
do you want to play again- type yes or no
yes
Enter the number of dice: 1
You rolled: 7
Total: 40
do you want to play again- type yes or no
no