【问题标题】:Will immediately add null even if I'm not typing即使我没有输入,也会立即添加 null
【发布时间】:2014-03-09 11:07:31
【问题描述】:

我无法解决关于“服务器已添加空值”的问题。 它不会先进入菜单来处理数据。

这也类似于编写客户端到服务器的问题。

这是我的代码:

学生:

import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class Student {
   public static void main(String args[]) {
      PrintWriter out = null;
      Scanner sc = new Scanner (System.in);

      //initialization

      String student = " ";
      String id = " ";
      String name = " ";

      try {
         Socket skt = new Socket("localhost", 1234);
         out = new PrintWriter(skt.getOutputStream(), true);

         while (name.equals("exit")) { //never ending menu
                 System.out.print("Please enter name: ");
                 name = sc.nextLine();
                 System.out.print("Please enter ID Number: ");
                 id = sc.nextLine();
                 student = name +" - "+ id;
                 out.print(student);                 
             }


      } catch(Exception e) {
          System.out.println("Whoops! It didn't work.");

      } finally {
          if (out != null) {
              try {
                  out.close();

      } catch (Exception e) {

              }
          }
      }
   }
}

服务器:

import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class Server {
   public static void main(String args[]) {
      Scanner sc = new Scanner (System.in);
      ArrayList<String> collector = new ArrayList<String>();
      String x = "";
      try {
         ServerSocket srvr = new ServerSocket(1234);
         Socket skt = srvr.accept();
         BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));

         x = in.readLine();
         collector.add(x);
         System.out.println("Server has added "+collector.get(collector.size()-1));


      }
      catch(Exception e) {
         e.printStackTrace();
         System.out.print("Whoops! It didn't work!\n");
      }
   }
}

知道有什么问题吗?

【问题讨论】:

    标签: java string sockets io


    【解决方案1】:

    根据“永无止境的菜单”条件select == 2,您对int select = 0; 的初始化以及对select 的其他写入,您将永远执行循环中的代码。 p>

    【讨论】:

    • 将我的代码更改为 name.equals("quit");还是不行。我怎样才能让我的服务器永远不会终止?我做了一个布尔 isStopped 变量,但它返回它不起作用
    • 哪个值在进入循环之前保持select,哪个值正在被测试?
    • 我实际上删除了选择。我将其替换为 name.equals("exit");这样如果我输入它,它将终止。
    • 已更新。由于连接速度慢,我没有立即更新我的代码。
    • 再一次,在进入循环之前哪个值持有name,以及正在测试哪个值?
    【解决方案2】:

    你的循环永远不会像你设置的那样执行select = 0

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 2017-10-24
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2016-02-19
      • 2020-12-07
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多