while循环没有停止,当有空格时它会断线。我想读完整行

时间:2016-10-24 11:02:22

标签: java decorator

public abstract class Decorator extends InputStream {

    public abstract StringBuilder operation();
}

//--------------------------------------------------//

public class UpperCaseToLowerCase extends Decorator {

    BufferedInputStream bis = null;

    public UpperCaseToLowerCase(BufferedInputStream bis) {
        this.bis = bis;
    }

    @Override
    public int read() throws IOException {
        return bis.read();
    }

    @Override
    public StringBuilder operation() {
        StringBuilder sb = new StringBuilder();
        try {
            int readInt = bis.read();
            String line = "";
            while (readInt != 1) {
                line = (char) readInt + "";
                sb = sb.append(line.toLowerCase());
                if (line.trim().equals(" ")) {
                    bis.close();
                    break;
                } else {
                    readInt = bis.read();
                }

            }
            bis.close();
        } catch (IOException ex) {
            Logger.getLogger(UpperCaseToLowerCase.class.getName()).log(Level.SEVERE, null, ex);
        }

        return sb;
    }

}


//------------------------------------

public class Main {

    public static void main(String[] args) {
        BufferedInputStream bis = null;
        System.out.print("Enter text     ---> ");
        bis = new BufferedInputStream(System.in);
        UpperCaseToLowerCase uctlc = new UpperCaseToLowerCase(bis);
        StringBuilder sb = uctlc.operation();
        System.out.println("To LowerCase ---> " + sb.toString());
    }
}

1 个答案:

答案 0 :(得分:0)

我试试这个并且有效

@Override
public StringBuilder operation() {
    StringBuilder sb = new StringBuilder();
    try {
        do {  
            int readint = bis.read();
            System.out.print("");
            String line = (char) readint + "";
            sb = sb.append(line.toLowerCase());
        } while (bis.available() > 0);
        bis.close();
    } catch (IOException ex) {
        Logger.getLogger(UpperCaseToLowerCase.class.getName()).log(Level.SEVERE, null, ex);
    }
    return sb;
}

但是如果删除System.out.print("");则无法正常工作!