Problems with Making a Highscore and Loops and Overall Issues
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 num开发者_运维技巧ber 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();
}
}
Some remarks:
- In the class
Score
the constructorScore()
is unnecessary since you don't use it. - You have a typo in the
ToString
method of that class. It should betoString
, starting with a lowercase letter. - You can make all three fields of the
Score
classfinal
. 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".
精彩评论