即使我没有输入,也会立即添加null

时间:2014-03-09 11:07:32

标签: java string sockets io

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

这类似于将客户端写入服务器问题。

这是我的代码:

学生:

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");
      }
   }
}

知道什么是错的吗?

2 个答案:

答案 0 :(得分:0)

根据“永无止境的菜单” - 条件select == 2,您int select = 0;的初始化以及select的其他任何着作都不会从不执行代码在循环中。

答案 1 :(得分:0)

您的循环将永远不会执行,因为您设置了select = 0