2015-11-01 70 views
1

我必须编写一个用户界面,它从命令屏幕接收数据并使用它访问链接列表类中的方法。它们都在同一个文件中,并且节点类已经写好了,它编译得很好。如果有人能帮我弄清楚为什么它只读取三条命令,比如我的狗,我的猫,p,然后说java.io.IOException:流关闭。我还检查了是否增加了空格,即指挥我的狗猫,我的鸟,p影响了它读取的行数,但它没有。例外情况也是如此。任何提示将非常感谢。我的输入只能读取三个命令,而不会读取它所读取的内容?

public static void main(String[] args){ 
    linkedlist link= new linkedlist(); 
    int n=0; 
    System.out.println("Type a command\n"); 
     try{ 
     BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); 
      s=in.readLine(); 
      while(in.readLine()!=null){ 
       s=in.readLine(); 
       char first=s.charAt(0); 
       int space= s.indexOf(" "); 
       while(space<=n){ 
        if(first=='i'){ 
         String w=s.substring(space); 
         link.insert(w); 
        } 
        if(first=='d'){ 
         String w=s.substring(space); 
         link.delete(w); 
         link.printlist(); 
        } 
        if(first=='f'){ 
         String w=s.substring(space); 
         link.find(w); 
         link.printlist(); 
        } 
        if(first== 'p'){ 
         link.printlist(); 
        } 
        n++; 
       } 
       in.close(); 
      } 
      }catch(Exception e) {System.out.println("Ack!: " + e);} 
} 

回答

1

流关闭错误意味着您正试图在关闭后写入。格式化你这样的代码:

Open in stream on this line before try 
try { 
    Do processing here 
    ..... 
} 
catch(Exception e) 
{ 
    .... 
} 
finally 
{ 
    close stream here 
} 

finally块将运行需要运行的try/catch后运行代码,这样就把流接近那里。

+1

谢谢解决了这个问题,但现在它不输出任何东西。我应该输出在finally块中。我不这么认为,但我很困惑。 – Haukka

+1

什么部分不输出 - catch中的Ack还是“输入命令”或其他? –

+1

任何方法 – Haukka

0

请尝试将while(in.readLine()!=null)循环后移出in.close();。目前,BufferedReader in在while循环内部被关闭,因此当while循环尝试检查in.readLine()!=null条件时,它实际上会尝试访问已关闭的in

+1

感谢您的帮助。但现在它不会输出任何东西。即使在我的链表类中,printlst包含System.out.println – Haukka