如何修改此Client类以从字符串数组(而不是标准输入)读取输入?

时间:2015-07-11 00:22:40

标签: java static bufferedreader

我在Java Client类中有以下代码(它是KnockKnock client/server pair):

   try {
      kkSocket = new Socket("localhost", 4444);
      out = new PrintWriter(kkSocket.getOutputStream(), true);
      in =  KKJokes[0]; //new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
      // in2 = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
    }

我想让它自动从String数组中读取(包含所有那些预定义的Jokes),如下所示:

       String KKJokes[] =  {"Who's there?", "Turnip who?", 
           "y", "Who's there?", "Who's there?", "blah" };
        /* more cod */
       try {
          kkSocket = new Socket("localhost", 4444);
          out = new PrintWriter(kkSocket.getOutputStream(), true);

       for (int i = 0; i< KKJokes.length; i++) {
          in =  new BufferedReader( new InputStreamReader( KKJokes[i] )) ; 
       }
      }

但这不起作用,它给出了:

KnockKnockClientRedux.java:33: non-static variable KKJokes cannot be referenced from a static context
      for (int i = 0; i< KKJokes.length; i++) {
                         ^ KnockKnockClientRedux.java:34: non-static variable KKJokes cannot be referenced from a static context
      in =  new BufferedReader( new InputStreamReader( KKJokes[i] )) ; //new Buf feredReader(new InputStreamReader(kkSocket.getInputStream()));
                                                       ^ KnockKnockClientRedux.java:34: cannot find symbol symbol  : constructor InputStreamReader(java.lang.String) location: class java.io.InputStreamReader
      in =  new BufferedReader( new InputStreamReader( KKJokes[i] )) ; //new Buf feredReader(new InputStreamReader(kkSocket.getInputStream()));

编辑:从文本文件中读取会不会更容易?也许我会在文本文件中垂直列出所有KnockNock笑话行。这样,在FileReader代码

中交换kkSocket.getInputStream()似乎更容易

1 个答案:

答案 0 :(得分:1)

编译器消息告诉它全部。试试

static String KKJokes[] =  {"Who's there?", "Turnip who?", 
       "y", "Who's there?", "Who's there?", "blah" };

第二个问题可以通过以下方式解决:

new InputStreamReader( new ByteArrayInputStream(KKJokes[i].getBytes() )