简体   繁体   English

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

[英]How do I modify this Client class to read input from an array of Strings (rather than from standard input)?

I have the following code, in a Java Client class ( it's this KnockKnock client/server pair ) : 我在Java Client类中有以下代码(这是此KnockKnock客户端/服务器对 ):

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

I want to have it automatically read from a String array (that contains all those predefined Jokes ) , something like this : 我想让它自动从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] )) ; 
       }
      }

But this doesn't work, it gives : 但这不起作用,它给出了:

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()));

EDIT: Wouldn't it be easier to just read from a text file? 编辑:从文本文件中读取会不会更容易? Maybe I'll list all the KnockNock joke lines vertically in a text file. 也许我会在文本文件中垂直列出所有的KnockNock笑话行。 That way, it seems easier to swap in a FileReader for the kkSocket.getInputStream() code 这样,在FileReader交换kkSocket.getInputStream()代码似乎更容易。

The compiler message tells it all. 编译器消息说明了一切。 Try with 试试看

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

The second problem can be solved with: 第二个问题可以通过以下方法解决:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM