java.lang.NullPointerException - не может найти пустую переменную

1

Мне не нравится задавать такой вопрос, но я новичок в программировании на Java... Как и вчера. Я пытаюсь объединить сервер и графический интерфейс, но у меня есть эта проблема. Извините за простой вопрос.

    * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.

import java.awt.*;
import java.awt.event.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.*;



/*
 * The chat client thread. This client thread opens the input and the output
 * streams for a particular client, ask the client name, informs all the
 * clients connected to the server about the fact that a new client has joined
 * the chat room, and as long as it receive data, echos that data back to all
 * other clients. The thread broadcast the incoming messages to all clients and
 * routes the private message to the particular client. When a client leaves the
 * chat room this thread informs also all the clients about that and terminates.
 */
class clientThread extends Thread {

  private String clientName = null;
  private DataInputStream is = null;
  private PrintStream os = null;
  private Socket clientSocket = null;
  private final clientThread[] threads;
  private int maxClientsCount;

  public clientThread(Socket clientSocket, clientThread[] threads) {
    this.clientSocket = clientSocket;
    this.threads = threads;
    maxClientsCount = threads.length;
  }

  @SuppressWarnings("deprecation")
public void run() {
    int maxClientsCount = this.maxClientsCount;
    clientThread[] threads = this.threads;

    try {
      /*
       * Create input and output streams for this client.
       */
      is = new DataInputStream(clientSocket.getInputStream());
      os = new PrintStream(clientSocket.getOutputStream());
      String name;
      while (true) {
        os.println("Enter your name.");
        name = is.readLine().trim();
        if (name.indexOf('@') == -1) {
          break;
        } else {
          os.println("The name should not contain '@' character.");
        }
      }

      /* Welcome the new the client. */
      os.println("Welcome " + name
          + " to our chat room.\nTo leave enter /quit in a new line.");
      synchronized (this) {
        for (int i = 0; i < maxClientsCount; i++) {
          if (threads[i] != null && threads[i] == this) {
            clientName = "@" + name;
            break;
          }
        }
        for (int i = 0; i < maxClientsCount; i++) {
          if (threads[i] != null && threads[i] != this) {
            threads[i].os.println("*** A new user " + name
                + " entered the chat room !!! ***");
          }
        }
      }
      /* Start the conversation. */
      while (true) {
        String line = is.readLine();
        if (line.startsWith("/quit")) {
          break;
        }
        /* If the message is private sent it to the given client. */
        if (line.startsWith("@")) {
          String[] words = line.split("\\s", 2);
          if (words.length > 1 && words[1] != null) {
            words[1] = words[1].trim();
            if (!words[1].isEmpty()) {
              synchronized (this) {
                for (int i = 0; i < maxClientsCount; i++) {
                  if (threads[i] != null && threads[i] != this
                      && threads[i].clientName != null
                      && threads[i].clientName.equals(words[0])) {
                    threads[i].os.println("<" + name + "> " + words[1]);
                    /*
                     * Echo this message to let the client know the private
                     * message was sent.
                     */
                    this.os.println(">" + name + "> " + words[1]);
                    break;
                  }
                }
              }
            }
          }
        } else {
          /* The message is public, broadcast it to all other clients. */
          synchronized (this) {
            for (int i = 0; i < maxClientsCount; i++) {
              if (threads[i] != null && threads[i].clientName != null) {
                threads[i].os.println("<" + name + "> " + line);
              }
            }
          }
        }
      }
      synchronized (this) {
        for (int i = 0; i < maxClientsCount; i++) {
          if (threads[i] != null && threads[i] != this
              && threads[i].clientName != null) {
            threads[i].os.println("*** The user " + name
                + " is leaving the chat room !!! ***");
          }
        }
      }
      os.println("*** Bye " + name + " ***");

      /*
       * Clean up. Set the current thread variable to null so that a new client
       * could be accepted by the server.
       */
      synchronized (this) {
        for (int i = 0; i < maxClientsCount; i++) {
          if (threads[i] == this) {
            threads[i] = null;
          }
        }
      }
      /*
       * Close the output stream, close the input stream, close the socket.
       */
      is.close();
      os.close();
      clientSocket.close();
    } catch (IOException e) {
    }
  }
}

/*
 * A chat server that delivers public and private messages.
 */
class DynamicWrite {

  // The server socket.
  private static ServerSocket serverSocket = null;
  // The client socket.
  private static Socket clientSocket = null;

  // This chat server can accept up to maxClientsCount clients' connections.
  private static final int maxClientsCount = 10;
  private static final clientThread[] threads = new clientThread[maxClientsCount];

  static void start(int args) {

    // The default port number.
    int portNumber = 5556;

    TextDemo.textArea.append("Now using port 5556");

    //Make sure the new text is visible, even if there
    //was a selection in the text area.
    TextDemo.textArea.setCaretPosition(TextDemo.textArea.getDocument().getLength());

    /*
     * Open a server socket on the portNumber (default 2222). Note that we can
     * not choose a port less than 1023 if we are not privileged users (root).
     */
    try {
      serverSocket = new ServerSocket(portNumber);
    } catch (IOException e) {
      System.out.println(e);
    }

    /*
     * Create a client socket for each connection and pass it to a new client
     * thread.
     */
    while (true) {
      try {
        clientSocket = serverSocket.accept();
        int i = 0;
        for (i = 0; i < maxClientsCount; i++) {
          if (threads[i] == null) {
            (threads[i] = new clientThread(clientSocket, threads)).start();
            break;
          }
        }
        if (i == maxClientsCount) {
          PrintStream os = new PrintStream(clientSocket.getOutputStream());
          os.println("Server too busy. Try later.");
          os.close();
          clientSocket.close();
        }
      } catch (IOException e) {
        System.out.println(e);
      }
    }
  }
}

@SuppressWarnings("serial")
public class TextDemo extends JPanel {
    static JTextArea textArea;
    final static String newline = "\n";

    public TextDemo() {
        super(new GridBagLayout());

        textArea = new JTextArea(5, 20);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);

        //Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);

        JPanel panel = new JPanel();
        scrollPane.setColumnHeaderView(panel);

        JButton btnTest = new JButton("Test");
        btnTest.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                textArea.append("Yuup" + newline);

                //Make sure the new text is visible, even if there
                //was a selection in the text area.
                textArea.setCaretPosition(textArea.getDocument().getLength());
            }
        });
        panel.add(btnTest);
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("TextDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add contents to the window.
        frame.getContentPane().add(new TextDemo());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {        
        //Schedule a job for the event dispatch thread:
        //creating and showing this application GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
        DynamicWrite.start(5556);
    }
}

Так оно и есть. Меня бросают

Exception in thread "main" java.lang.NullPointerException
    at DynamicWrite.start(TextDemo.java:203)
    at TextDemo.main(TextDemo.java:311)"

когда я пытаюсь запустить его. И я не могу, чтобы жизнь меня находила проблему. Я знаю, что мне есть чему поучиться. Спасибо, ~ P

Теги:
pointers
exception
null

2 ответа

0
Лучший ответ

Я предполагаю, что вы забыли инициализировать переменную, так как это обычный случай для исключения нулевого указателя. Быстро посмотрите на свой код, и я думаю, что он находится под TextDemo. Вероятно, это был бы static JTextArea textArea = new JTextArea(); ,

  • 0
    Как ты...!? Я только что удалил это некоторое время назад, не зная последствий. Я думал, что я сделал с этой переменной. Ну, теперь нулевой указатель исчез, но я столкнулся с другой проблемой. Символы, которые я намеревался напечатать в области текста, не печатаются.
  • 0
    Потому что я столько раз сталкивался с одной и той же проблемой, она застряла у меня в голове. Я не могу помочь с вашей новой проблемой, так как я менее знаком с ней. Отметьте это как ответ, чтобы закрыть вопрос. Благодарю.
Показать ещё 8 комментариев
0

Проверьте эту часть.

@SuppressWarnings("deprecation")
public void run() {
    int maxClientsCount = this.maxClientsCount;
    clientThread[] threads = this.threads;

Вы уже заявили об этом 2. Попробуйте использовать другое имя для этого 2 или избегайте "int" и "clientThread []". Проверьте это и скажите, работает ли это.

  • 0
    Используете ли вы какие-либо IDE, такие как NetBeans или Eclipse?
  • 0
    Затмение на самом деле. И так как я только начал java вчера, вам придется объяснить мне, что вы подразумеваете в своем ответе «это 2».
Показать ещё 8 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню