1
import java.util.*;
import java.util.Random;

public class Playoffs
{
  public static Scanner scan = new Scanner(System.in);

  public static void main(String [] args)
  {   
    boolean validNumber;
    int game1;

    System.out.print("What is the % chance that team 1 will win the game?");

    do{
      game1 = scan.nextInt();
      validNumber = game1 >= 0 && game1 <=100;

      if(!validNumber){
        System.out.println("INVALID NUMBER ENTERED: NOT BETWEEN 0 AND 100");
        System.out.print("Enter a valid number between 0 and 100: ");
      }
    }while(!validNumber);
    System.out.println("Team 1 has a " + game1 + "% chance of winning.");

The code below should generate a random number between 0 (inclusive) and 100 (exclusive), stating that if the random number is less than the percentage the user input, team 1 will win, and team 2 should win if the random number is greater than the percentage entered, but it always comes out that team 1 wins

    Random rand = new Random(100);
    int randomNumber = rand.nextInt();
    int oneGame = simulateOneGame(game1, randomNumber);

    if(oneGame == 1){
      System.out.println("\nTeam 1 has won the game");
    }else if(oneGame == 0){
      System.out.println("\nTeam 2 has won the game");
    }
  }

  public static int simulateOneGame(int game1, int randomNumber)
  {
    int result=0;
    if (randomNumber < game1) {
      result += 1;
    } else if(randomNumber > game1){
      result += 0;
    }
    return result;
  } 
}

1 Answers1

4

This code doesn't generate a number between 0 and 100:

Random rand = new Random(100);
int randomNumber = rand.nextInt();

rand.nextInt() can return any number between Integer.MIN_VALUE and Integer.MAX_VALUE, but since you are using a constant seed (100), you get the same "random" number every time - -1193959466 in your case.

This code does what you want:

Random rand = new Random();
int randomNumber = rand.nextInt(100);

Also note that you don't have to create a new Random instance in each iteration. It's enough to create one instance.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • int nextInt(int bound) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. https://docs.oracle.com/javase/8/docs/api/java/util/Random.html – Kareem Sasa Oct 23 '17 at 05:32
  • 2
    @KareemSasa That's correct, but you didn't use that method in your code. You used `int nextInt()`. – Eran Oct 23 '17 at 05:34