Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.JOptionPane;
- public class assignment8 {
- public static void main(String[] args) {
- int round = 1;
- int bustPlayers = 0;
- while(round < 4){
- double secretPrice = getSecretPrice();
- double[] playerGuess = getPlayerGuess();
- for(int i = 0; i < playerGuess.length; i++){
- if (playerGuess[i] > secretPrice) {
- bustPlayers++;
- }
- String compareGuess = processCompareGuess(secretPrice, playerGuess);
- }
- if (bustPlayers == playerGuess.length) {
- JOptionPane.showMessageDialog("All players have busted, round will replay");
- continue;
- }
- String compareGuess = processCompareGuess(secretPrice, playerGuess);
- round++;
- }
- displayResults(nearest, playerGuess);
- }
- public static double getSecretPrice() {
- double secretPrice;
- return secretPrice = (Double.parseDouble(JOptionPane.showInputDialog("Please enter the secret price")));
- }
- public static double[] getPlayerGuess() {
- double playerGuess[] = new double[3];
- for(int i = 0; i < playerGuess.length; i++){
- int player = (1 + i);{
- if ( player == 1){
- player = 1;
- }
- //error handling to make sure the entry is a positive number and not a letter
- while (true){
- try{
- playerGuess[i] = Double.parseDouble(JOptionPane.showInputDialog(null, "Player"+player+", Please enter your guess"));
- if (playerGuess[i] < 0) {
- JOptionPane.showMessageDialog(null,"No Negative Entries");
- continue;
- }
- }
- catch (IllegalArgumentException e) {
- JOptionPane.showMessageDialog(null,"Entries Must Be Numbers");
- continue;
- }
- break;
- }
- for(int j = 0; j < i; j++) {
- if (playerGuess[i] == playerGuess[j]) {
- i--;
- playerGuess[i] = Double.parseDouble(JOptionPane.showInputDialog(null, "Player"+player+", Please enter a new guess, that guess already exists"));
- }
- }
- }
- }
- return playerGuess;
- }
- public static String processCompareGuess (double secretPrice, double[] playerGuess) {
- double bestDistanceFoundYet = Double.MAX_VALUE;
- String instantWinnerMessage;
- String instantWinner = null;
- String nearest = null;
- // We iterate on the array...
- for (int i = 0; i < playerGuess.length; i++) {
- // if we found the desired number, we return it.
- if (playerGuess[i] == secretPrice) {
- return instantWinner = Double.toString(playerGuess[i]);
- } else {
- // else, we consider the difference between the desired number and the current number in the array.
- double d = Math.abs(secretPrice - playerGuess[i]);
- if (d < bestDistanceFoundYet) {
- // For the moment, this value is the nearest to the desired number...
- nearest = ("Player" + i + "is the cloest guess with" + playerGuess[i]);
- d = bestDistanceFoundYet;
- }
- }
- }
- return nearest;
- }
- public static void displayResults(String nearest, double[] playerGuess) {
- JOptionPane.showMessageDialog(null, nearest);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement