控制檯錄入字節流

鍵盤讀取錄入當錄入的字符爲quit時,程序退出 否則 則將所有字符轉變成大寫輸出
1.使用scanner循環錄入,判斷錄入的字符串是否和quit相等,相等則退出,不相等則將字符串大寫出
2.自己創建一個控制檯的輸入流,來錄入字符串(模擬Scanner)

// 獲取一個存儲字符串的容器
StringBuilder sb = new StringBuilder();
// 獲取字節輸入流 來讀取控制檯輸入的字符串
InputStream in = System.in;
// 一個一個讀效率太過於滴 循環讀的話又會將回車\r換行\n讀取出來 所以就要進行判斷
// int ch = in.read();
// System.out.println(ch); //97 a
// System.out.println(in.read()); //98 b
// System.out.println(in.read()); //99 c
// int ch1 = in.read();
// System.out.println(ch1); //100 d
// System.out.println(in.read()); //13 \r
// System.out.println(in.read()); //10 \n

/**
     * 循環讀取的操作
     */  

       int ch = 0 ; 
            while ((ch = in.read()) != -1) {
                if (ch == '\r') {
                    continue;
                } 
                if (ch == '\n') { 

// 當讀取到\n的時候就代表已經讀取完畢了回車換行也讀取進去了,也就可以判斷字符串是否與quit相等

    String result = sb.toString();
    if ("quit".equals(result)) {
        break;
        } else {

// 輸出大寫字符串

System.out.println(result.toUpperCase());
    sb.delete(0, sb.length());
    }
        } else { // 拼接其他字符串
                    sb.append((char)ch);
                }
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章