tags:

views:

95

answers:

2

Hey guys , thanx for the previus help..... This time it's homework meaning they want me to make a highscore that shows playername,score (tries it took) and time. Basically it wants:
To write a game in which a user is to guess a random number between 1 and 1000. The program should read a number from the keyboard, and print whether the guess was too high, too low or correct. When the user has guessed correctly, the program prints out the numbe of guesses made and time and the playername.When a game is started the program must print the entire high score list, sorted by the number of guesses in ascending order. Note: this list must be maintained as long as the game-object is alive! example without time;

Guess is too high!
> 813
Guess is too high!
> 811
**** CORRECT!
**** You guessed the correct number in 11 guesses
Please enter you name:
> niklas
Do you want to play again?(y/n)
 >y
Current highscore list:
Name Guesses
niklas 11

My questions are; is my code provided below enough to mainten these requirements, if not what should i add then because i Really don't know what to do? And please consider that I'm a still in learning phase So take it easy with the Comments :) Here is the code:

package testa;
import java.util.*;
import java.util.Scanner.*;
import java.util.ArrayList.*;


public class Main {
private static class Score {

 int playerScore = 0;
 double playerTime = 0;
 String playerName;

 public Score ()
 {
 }

 public Score (int playerScore, double playerTime, String playerName)
 {
  this.playerScore = playerScore;
  this.playerTime = playerTime;
  this.playerName = playerName;
 }

 public String ToString()
 {
  String scoreList = (playerScore + "\t\t" + playerTime + "\t\t" + playerName);

  return scoreList;
 }
}

private static void start() {

 int answer = (int) (Math.random() * 1000 + 1) ; 
 int tries = 0 ;

 int guess = -1;
 String name ;
 String quit = "quit";
 String y = "yes";
 String n = "no";
 String currentGuess;

 String another = ("y") ;
 Scanner input = new Scanner (System.in);

 ArrayList<Score> scores = new ArrayList<Score>();


    System.out.println( " Welcome to Guessing Game " ) ;
    System.out.print("Please enter a number between 1 and 1000 : ");
                    currentGuess = input.nextLine();
      long startTime = System.currentTimeMillis();





      do
      {


               if (currentGuess.equalsIgnoreCase(quit))
  {
   System.out.println("Leaving Us So Soon?");
   System.exit(0);
  }

               try    {
   guess = Integer.parseInt(currentGuess);
        } catch (NumberFormatException nfe) 
                        {
   System.out.println(" Dude Can You Read, Only Digits ");
                        currentGuess = input.nextLine();


   }

  if (guess < 1 || guess > 1000)
  {
   System.out.println("Stupid Guess I Wont Count That.");
                        currentGuess = input.nextLine();

  }
       if (guess < answer )
          {
   System.out.println("too low");
   currentGuess = input.nextLine();
                        tries++;
  }


    else if(guess  > answer )
  {
   System.out.println("too high");
   currentGuess = input.nextLine();
                        tries++;
  }


    else if (guess == answer)
  {       
   //stop stop watch
   long endTime = System.currentTimeMillis();
   //calculate game time
   long gameTime = endTime - startTime;
   System.out.println("You Rock Dude, Good Job!");

                        System.out.println("You guessed " + tries + " times in " + (int)(gameTime/1000) + " seconds.");
                        System.out.println("Please enter your name.");
            name = input.nextLine();
                          //create score object
   Score currentScore = new Score(tries, gameTime, name);
   //add score to arrayList
   scores.add(currentScore);


                     Scanner playGame = new Scanner(System.in);
                     System.out.print("Want to go again?(y/n).....");
                      if (currentGuess.equalsIgnoreCase(y))
   {
                     System.out.println("Guess \t Time in miliseconds \t Name");
    //print out high score list
    for (int i = 0;i < scores.size(); i++)
    {
    System.out.println(scores.get(i));
    }
     another = playGame.nextLine();
                                 Main.start();
   }
               //if user doesn't want to play again
   if (currentGuess.equalsIgnoreCase(n))
   {
    System.out.println("Guess \t Time in miliseconds \t Name");
    //print out high score list
    for (int i = 0;i < scores.size(); i++)
    {
    System.out.println(scores.get(i));
    }
                                System.out.println("Thanx For Playing.");
    System.exit(0);
                    }
          }

        } while (guess != answer);



}

public static void main(String[] args) {
   ArrayList<Score> scores = new ArrayList<Score>();
    Main.start();
    }
}
A: 

Some remarks:

  • In the class Score the constructor Score() is unnecessary since you don't use it.
  • You have a typo in the ToString method of that class. It should be toString, starting with a lowercase letter.
  • You can make all three fields of the Score class final. That way they cannot be changed after the constructor has finished.
  • You have many unused local variables. You can remove them, which makes the code clearer.

Back to your original question regarding the high score table. I once had to do the very same task and I made the highscore its own class. It looked approximately like this:

public class HighScore {

  private final int maxEntries;
  private List<Score> scores = new ArrayList<Score>();

  /**
   * Creates a new highscore table that keeps only <i>maxEntries</i> best entries.
   */
  public HighScore(int maxEntries) {
    this.maxEntries = maxEntries;
  }

  /**
   * Adds an entry to the highscore table if it is good enough.
   *
   * @return {@code true} if the score has been added, {@code false} otherwise.
   */
  public boolean add(Score score) {
    // TODO: add the entry
    // TODO: make sure the entries are sorted correctly; some hints: Collection.sort, Comparator
    // TODO: throw out the worst entry if there are more than maxEntries
  }

  /**
   * Returns the highscore table.
   *
   * @return The highscore entries in the correct order. The first entry is the best one.
   */
  public List<Score> getTable() {
    return Collections.unmodifiableList(scores);
  }

}

When you have such a class, you can easily write some tests to make sure it works correctly. For example:

@Test
public void testEmptyTable() {
  HighScore highscore = new HighScore(5);
  assertTrue(highscore.getTable().isEmpty());
  assertTrue(highscore.add(new Score(1, 0.5, "Caesar Primus")));
  assertFalse(highscore.getTable().isEmpty());
}

Testing is a great tool to make sure that your code works for the basic cases. A good keyword for further search is "JUnit".

Roland Illig
A: 

Ok lets look at this from the ground level and build up the application as such.

1) We need to track the number of guesses made, this will later refer to the score:

public void incrementScore()
{
myCurrentScore++;
}

2) We now need to address if the guess made was correct:
public boolean evaluateGuess(int playerGuess, int answer)
{
return playerGuess==answer;
}

3) We need to override toString:
public String toString()
{
return this.name + " " + this.playerScore + " " + this.time;
}

4) We need to sort the elements in order:
public void sortList(List<Integer> listToSort)
{
Collections.sort(listToSort);
}

This should be enough to get you put back on the right track.

Woot4Moo
The first method is useless. It just increments a local variable. From the outside, there is no visible effect. The fourth method is also useless. You don't want to sort integers, you want to sort complete highscore entries.
Roland Illig
Actually Roland, you really only care about the integers that belong to the current user object, so sorting the integers is correct in this instance. Additionally the first method is useful in this instance as it would be updating the current objects field, regardless of what my names are in comparison to his. It is far wiser to do this than to have random playerScore++'s everywhere
Woot4Moo
Except the playerScore won't be incremented when you come out of that method.
AHungerArtist
here ill change it to avoid all of the confusion.
Woot4Moo
Yes, that version actually works as you intended. But it wasn't just confusion. Since you didn't use 'this' when the names were the same, it really was only incrementing the passed in playerScore and not the instance one. This poster seems to be pretty new to things and if he used your code, that's something he could easily overlook.
AHungerArtist
Which Is why I made the additional name change :)
Woot4Moo