Avatar billede drejs Nybegynder
25. november 2003 - 23:39 Der er 5 kommentarer

Problemer med nullPointerException

Hej. Vi er en flok nybegyndere i Java, der har fået til opgave at lave en highscore-server til et simpelt tekstbaseret spil. Problemet er nu, at da File-klassens saveToFile metode blev tilføjet, begyndte programmet at melde om nullPointerException i følgende linier:
  ScoreComparer - linie 5
  HighScoreServer - linie 19, 36, 78, 98, 132

Er der nogen der kan hjælpe?? Problemet er også, at vi ikke har lavet al koden fra bunden, men har bygget videre på et eksisterende program fra vores underviser.

Koden er som følger:
-----
import java.io.*;
import java.net.*;
import java.util.*;

/**
* A simple server listening for data on a socket and writing it back
* in upper case.
*
* @author mik
* @version 1.0
*/
public class HighScoreServer
{
    Score highScore[] = new Score[11];
    public static void main(String argv[])
        throws Exception
       
    {
        HighScoreServer server = new HighScoreServer();
        server.start();
    }
    private Parser parser;
    private File file;
                 
    /**
    * Constructor for objects of class HighScoreServer
    */
    public HighScoreServer()
    {
        parser = new Parser();
        file = new File();
     
      for(int i = 0;i < file.maxNumberOfScores();i++)
        {
            Command command = parser.getCommand(file.getInputLine(i));
            processCommand(command);
        }
    }

    /**
    */
    public int start()
        throws IOException
    {
        System.out.println("Starting server.");
       
        String clientReturn;
        String clientSentence;

        ServerSocket welcomeSocket = new ServerSocket(6789);
 
        while(true) {
            System.out.println("Waiting for request...");
            Socket connectionSocket = welcomeSocket.accept();

            BufferedReader inFromClient =
                new BufferedReader(new
                InputStreamReader(connectionSocket.getInputStream()));

            DataOutputStream  outToClient =
                new DataOutputStream(connectionSocket.getOutputStream());

            clientSentence = inFromClient.readLine();
            System.out.println("Received: " + clientSentence);

            Command command = parser.getCommand(clientSentence);
            clientReturn = processCommand(command);
           
            outToClient.writeBytes(clientReturn);
        }
    }
    public String processCommand(Command command)
    {
        String serverAnswer = "";
        String commandWord = command.getCommandWord();
        if (commandWord.equals("add"))
        {
            serverAnswer = addHighScore(command);
        }
        else if (commandWord.equals("check"))
        {
            serverAnswer = checkScore(command);
        }
        else if (commandWord.equals("list"))
        {
            serverAnswer = listHighScore(command);
        }
        return serverAnswer;
    }
   
    public String addHighScore(Command command)
    {
        String serverAnswer;
        int highScoreNumber = Integer.parseInt(command.getSecondWord());
        String playerName = command.getThirdWord();
        int playerScore = Integer.parseInt(command.getFourthWord());
        highScore[highScoreNumber] = new Score(playerName,playerScore);
        sortHighScore();
//        file.saveFile();
        serverAnswer = "ok";
        return serverAnswer;
    }
   
  private String checkScore(Command command)
    {
        String serverAnswer;
        int playerScore = Integer.parseInt(command.getSecondWord());
        if(playerScore > highScore[9].getScore())
        {
            serverAnswer = "ok";
        }
        else
        {
            serverAnswer = "noscore";
        }
        return serverAnswer;         
    }
   
    private String listHighScore(Command command)
    {
        String serverAnswer = "";

        for (int i=0;i<10;i++)
        {
            serverAnswer += "" + (i+1) + " - " + highScore[i] + "\n";
        }
        return serverAnswer;
    }
   
    private void sortHighScore()
    {
        Arrays.sort(highScore,new ScoreComparer());
    }
   
}
-----
import java.util.*;

class Score
{
    private String name;
    private int score;

    public Score(String name, int score)
    {
        this.name = name;
        this.score = score;
    }

    public int getScore()
    {
        return score;
    }

    public String toString()
    {
        return name + " " + score;
    }
}
-----
public class ScoreComparer implements java.util.Comparator
{
    public int compare(Object o1,Object o2)
    {
        return ((Score)o2).getScore()-((Score)o1).getScore();
    }
}
-----
import java.io.*;
import java.util.*;


/**
* Write a description of class File here.
*
* @author (your name)
* @version (a version number or a date)
*/

public class File
{
    int maxScores;
    String fileName;
    private ArrayList inputLines;
   
    public File()
    {
        maxScores = 11;
        inputLines = new ArrayList();
        fileName = "highscores.dat";
        loadFile();
    }
   
    private void loadFile()
    {
        try
        {
            FileReader readFromFile = new FileReader(fileName);
            BufferedReader inFromFile = new BufferedReader(readFromFile);
            for(int i = 0;i < maxScores;i++)
            {
                String inputLine = inFromFile.readLine();
                inputLines.add(inputLine);
            }
            inFromFile.close();
        }
        catch(FileNotFoundException exeption)
        {
            System.out.println("The file " + fileName + " was not found.");
        }
        catch(IOException exception)
        {
            System.out.println(exception);
        }
    }
   
//    public void saveFile()
//    {
//        FileWriter writeToFile = new FileWriter(fileName);
//        BufferedWriter outToFile = new BufferedWriter(writeToFile);
//        PrintWriter outFile = new PrintWriter(outToFile);
//        for(int i = 0;i < maxScores;i++)
//        {
//            String outputLine = (String)inputLines.get(i);
//            outFile.print(outputLine + "\n");
//        }
//        outFile.close();
//    }
   
    public int maxNumberOfScores()
    {
        return maxScores;
    }
   
    public String getInputLine(int lineNumber)
    {
        String returnString = (String)inputLines.get(lineNumber);
        return returnString;
    }
   
    public void addInputLine(int lineNumber,String inputString)
    {
        inputLines.set(lineNumber,inputString);
    }
}
-----
/**
* This class holds information about a command that was issued by the user.
* A command currently consists of two strings: a command word and a second
* word (for example, if the command was "take map", then the two strings
* obviously are "take" and "map").
*
* The way this is used is: Commands are already checked for being valid
* command words. If the user entered an invalid command (a word that is not
* known) then the command word is <null>.
*
* If the command had only one word, then the second word is <null>.
*
*/

public class Command
{
    private String commandWord;
    private String secondWord;
    private String thirdWord;
    private String fourthWord;

    /**
    * Create a command object. First and second word must be supplied, but
    * either one (or both) can be null. The command word should be null to
    * indicate that this was a command that is not recognised by this game.
    */
    public Command(String firstWord, String secondWord, String thirdWord, String fourthWord)
    {
        commandWord = firstWord;
        this.secondWord = secondWord;
        this.thirdWord = thirdWord;
        this.fourthWord = fourthWord;
    }

    /**
    * Return the command word (the first word) of this command. If the
    * command was not understood, the result is null.
    */
    public String getCommandWord()
    {
        return commandWord;
    }

    /**
    * Return the second word of this command. Returns null if there was no
    * second word.
    */
    public String getSecondWord()
    {
        return secondWord;
    }
   
    public String getThirdWord()
    {
        return thirdWord;
    }
   
    public String getFourthWord()
    {
        return fourthWord;
    }
   

    /**
    * Return true if this command was not understood.
    */
    public boolean isUnknown()
    {
        return (commandWord == null);
    }

    /**
    * Return true if the command has a second, third and fourth word.
    */
    public boolean hasSecondWord()
    {
        return (secondWord != null);
    }
   
    public boolean hasThirdWord()
    {
        return (thirdWord != null);
    }
   
    public boolean hasFourthWord()
    {
        return (fourthWord != null);
    }
}
-----
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

/*
* This parser reads user input and tries to interpret it as an "Adventure"
* command. Every time it is called it reads a line from the terminal and
* tries to interpret the line as a two word command. It returns the command
* as an object of class Command.
*
* The parser has a set of known command words. It checks user input against
* the known commands, and if the input is not one of the known commands, it
* returns a command object that is marked as an unknown command.
*
*/

public class Parser
{

    private CommandWords commands;  // holds all valid command words

    public Parser()
    {
        commands = new CommandWords();
    }

    public Command getCommand(String inputFromClient)
    {
        String inputLine = inputFromClient;  // will hold the full input line
        String word1;
        String word2;
        String word3;
        String word4;
       
StringTokenizer tokenizer = new StringTokenizer(inputLine, ";");

        if(tokenizer.hasMoreTokens())
            word1 = tokenizer.nextToken();      // get first word
        else
            word1 = null;
        if(tokenizer.hasMoreTokens())
            word2 = tokenizer.nextToken();      // get second word
        else
            word2 = null;
        if(tokenizer.hasMoreTokens())
            word3 = tokenizer.nextToken();      // get third word
        else
            word3 = null;
        if(tokenizer.hasMoreTokens())
            word4 = tokenizer.nextToken();      // get fourth word
        else
            word4 = null;

        // note: we just ignore the rest of the input line.

        // Now check whether this word is known. If so, create a command
        // with it. If not, create a "null" command (for unknown command).

        if(commands.isCommand(word1))
            return new Command(word1, word2, word3, word4);
        else
            return new Command(null, word2, word3, word4);
    }
     
}
-----
/*
* This class is the main class of the "FedEx" application.
* "FedEx" is a very simple, text based adventure game.
*
* This class holds an enumeration of all command words known to the game.
* It is used to recognise commands as they are typed in.
*
* @author  Michael Kolling and David J. Barnes
* @version 1.0 (February 2002)
*/

class CommandWords
{
    // a constant array that holds all valid command words
    private static final String validCommands[] = {
        "check", "add", "list"
    };

    /**
    * Constructor - initialise the command words.
    */
    public CommandWords()
    {
        // nothing to do at the moment...
    }

    /**
    * Check whether a given String is a valid command word.
    * Return true if it is, false if it isn't.
    */
    public boolean isCommand(String aString)
    {
        for(int i = 0; i < validCommands.length; i++) {
            if(validCommands[i].equals(aString))
                return true;
        }
        // if we get here, the string was not found in the commands
        return false;
    }

}
----- TIL SIDST ET LILLE CLIENT-PROGRAM TIL AT TESTE MED --
import java.io.*;
import java.net.*;

/**
* SimpleClient is a simpel client class that sends a request
* to a server. (It actually sends an arbitrary text string,
* and then receives and diaplys the reply.)
*
* @author mik
* @version 1.0
*/
public class SimpleClient
{
    private BufferedReader inFromUser;
   
    public static void main(String argv[])
        throws UnknownHostException, IOException
    {
        SimpleClient client = new SimpleClient();
        client.start();
    }
   
    /**
    * Constructor for objects of class SimpleClient
    */
    public SimpleClient()
    {
        // create a buffered reader to read input from the terminal
        // (typed input from the user's keyboard)
        inFromUser =
            new BufferedReader(new InputStreamReader(System.in));
    }

    /**
    */
    public void start()
        throws UnknownHostException, IOException
    {
        Socket clientSocket = new Socket("localhost", 6789);

        DataOutputStream outToServer =
            new DataOutputStream(clientSocket.getOutputStream());

        BufferedReader inFromServer =
            new BufferedReader(new
            InputStreamReader(clientSocket.getInputStream()));

        System.out.print("Enter some text: ");
      String sentence = inFromUser.readLine() + ";";

        outToServer.writeBytes(sentence + '\n');

        String modifiedSentence = inFromServer.readLine();

        System.out.println("FROM SERVER: " + modifiedSentence);

        clientSocket.close();
                 
    }
}
Avatar billede erikjacobsen Ekspert
25. november 2003 - 23:44 #1
Står der noget i alle pladser i
  Score highScore[] = new Score[11];
?
Avatar billede drejs Nybegynder
26. november 2003 - 00:00 #2
Ja - de bliver indlæst fra en fil.
Avatar billede erikjacobsen Ekspert
26. november 2003 - 00:06 #3
Nååh... I public String addHighScore  kalder du sortering for hver
indsættelse (så vidt jeg kan se), og så er de vel ikke allesammen
udfyldt?
Avatar billede drejs Nybegynder
26. november 2003 - 19:28 #4
Jeps - Det var problemet! Tak for hjælpen. Post et svar, så får du pointene...
Avatar billede erikjacobsen Ekspert
26. november 2003 - 19:36 #5
nej tak, det er for vildt for mig når du opretter et spørgsmål med 150 p.
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester



IT-JOB

Udviklings- og Forenklingsstyrelsen

Erfaren teamleder til årsopgørelsen

Netcompany A/S

Test Specialist

Udviklings- og Forenklingsstyrelsen

Testmanager til Partsrepræsentation

Pharma Nord

PHP backend-udvikler