黑马程序员技术交流社区

标题: 怎样结束流? [打印本页]

作者: 吴亨    时间: 2011-12-17 20:09
标题: 怎样结束流?
import java.io.*;
public class TestByteArray {

        public static void main(String[] args) {
                byte[] buffer = "asadhjkk".getBytes();
                ByteArrayInputStream in = new ByteArrayInputStream(buffer);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                transform(in,out);
                transform(System.in,System.out);

        }

        public static  void transform(InputStream in,OutputStream out)
        {
                int ch1 = 0;
                int ch2 = 0;
                try{

                while((ch1 = in.read())!=-1)
                {
                  ch2 = Character.toUpperCase(ch1);
                  out.write(ch2);

                }
                if((out.toString()).equals("bye"))
                          System.in.close();
                System.out.println(out.toString());

        }
        catch(Exception ex){}
        }
}

怎样才能在输入“bye”之后结束程序了,我那段代码好像不行。

作者: 马伟奇    时间: 2011-12-17 20:19

import java.io.*;
public class TestByteArray {

        public static void main(String[] args) {
                byte[] buffer = "asadhjkk".getBytes();
                ByteArrayInputStream in = new ByteArrayInputStream(buffer);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                transform(in,out);
                transform(System.in,System.out);

        }

        public static  void transform(InputStream in,OutputStream out)
        {
                int ch1 = 0;
                int ch2 = 0;
                try{

                while((ch1 = in.read())!=-1)
                {
                  if((ch1).equals("bye"))
                          break;
                  ch2 = Character.toUpperCase(ch1);
                  out.write(ch2);

                }
               
                System.out.println(out.toString());

        }
        catch(Exception ex){}
        }
}
作者: songxingchao    时间: 2011-12-17 22:52
楼主第一次调用transform 没有问题,
第2次调用就有很多错误了,  transform(System.in,System.out);
首先System.out 不属于ByteArrayOutputStream 类型,out.write(ch2); 你的这句话并不能把ch2保存到out里面, out.write(ch2) 这这里相当于System.out.write(ch2),也就是把它打印在控制台上。
根据单步调试, 最后out的结果是一堆无意义的数据,不可能等于bye。
归根结底,楼主的函数不适用于System.in,System.out 这两个参数, 因为他们不是ByteArrayOutputStream  类型。
作者: 大梅    时间: 2011-12-18 19:42
可以将transform的返回值变成boolean型,当“bye”时返回true,否则返回false。在主函数中返回了true就直接return,否则继续。
作者: 黑马巩伟伟    时间: 2011-12-19 13:58
in在System类中的声明方式为“public static final InputStream in”,也就是说in是InputStream的一个对象,而楼主的 transform(System.in,System.out)此方法是将InputStream的对象传给了ByteArrayInputStream ,所以在调用时就会有问题。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2