0

I am trying to pass data from a String into a PrintWriter while simultaneously reading from a BufferedReader between two classes named Server.java and Client.java. My problem is that I am having trouble handling the exceptions that are being thrown from the block of code that reads data from the Scanner object (marked below).

Client.java

package root;

/**
 * @author Noah Teshima
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private Socket clientSocket;

    private BufferedReader bufferedReader;
    private InputStreamReader inputStreamReader;
    private PrintWriter printWriter;

    private Scanner scanner;

    public static void main(String[] args) {
        new Client("localhost", 1025);
    }

    public Client(String hostName, int portNumber) {
        try {
            this.clientSocket = new Socket(hostName, portNumber);
            this.bufferedReader = new BufferedReader(this.inputStreamReader = new InputStreamReader(this.clientSocket.getInputStream()));
            this.printWriter = new PrintWriter(clientSocket.getOutputStream());
            String msg = "",
                    msg2 = "";

            this.printWriter.println(this.getClass());
            this.printWriter.flush();
            System.out.println(this.getClass().getName() + " is connected to " + this.bufferedReader.readLine());

            while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem
                this.printWriter.println(this.getClass().getName() + ": " + msg);
                this.printWriter.flush();

                while((msg2 = this.bufferedReader.readLine()) != null) {
                    System.out.println(msg2);
                }
            }

            this.clientSocket.close();
        }catch(IOException exception) {
            exception.printStackTrace();
        }
    }
}

Stack trace::

Exception in thread "main" java.lang.NullPointerException
    at root.Client.<init>(Client.java:47)
    at root.Client.main(Client.java:25)

The code used to read from the BufferedReader and write to a PrintWriter is the same for both classes, so I only posted Client.java. If anyone would like to see the other class file, I would be happy to do so.

  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – almightyGOSU Jul 11 '15 at 02:40

1 Answers1

1

Before you use

while(!(msg = this.scanner.nextLine()).equals("exit")) { //Source of problem

You should have initialized the scanner.
The scanner object is null when you used it, and hence the NullPointerException.

I do not see a scanner = new Scanner(...); anywhere within your code,
maybe you have forgetten about it?

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41