2021-12-08_学习视频:写入转换流_学习题目:移动零
1. B站P244 写入转换流
/* 字符流: FileReader FileWriter BufferedReader BufferedWriter 字节流: FileInputStream FileOutputStream BufferedInputStream BufferedOutputStream 通过刚才的键盘录入一行数据并打印其大写,发现其实就是读一行数据的原理。 也就是readLine方法。 能不能直接readLine方法,来完成键盘录入的一行数据的读取呢? readLine方法是字符流BufferedReader类的方法。 而键盘录入的read方法是字节流InputStream的方法。 那么能不能将字节流转成字符流再使用字符流缓冲区的readLine方法呢? */ import java.io.*; class TransStreamDemo { public static void main(String[] args) throws IOException { // 获取键盘录入对象 // InputStream in = System.in; // 将字节流对象转成字符流对象,使用转换流。InputStreamReader // InputStreamReader isr = new InputStreamReader(in); // 为了提高效率,将字符流进行缓冲区技术高效操作。使用BufferedReader // BufferedReader bufr = new BufferedReader(isr); // 键盘的最常见写法。 BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); // OutputStream out = System.out; // OutputStreamWriter osw = new OutputStreamWriter(out); // BufferedWriter bufw = new BufferedWriter(osw); BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out)); String line = null; while ((line = bufr.readLine()) != null) { if ("over".equals(line)) { break; } // System.out.println(line.toUpperCase()); bufw.write(line.toUpperCase()); bufw.newLine(); bufw.flush(); } bufr.close(); } }
2. problem539:移动零
public class Solution { public void moveZeroes(int[] nums) { // 思路:定义两个指针,两个指针初始化都指向原数组的索引为0的位置, // 一个指针nextToBeChangePointer用于指向下一步将要对其进行替换的新数组的位置, // 另一个指针nextToBeScanPointer用于向右扫描原数组, // 情况1:若nextToBeScanPointer扫描到的值不等于0,则把这个值赋给nextToBeChangePointer指向的位置, // 然后两个指针分别右移一位, // 情况2:若nextToBeScanPointer扫描到的值等于0,则nextToBeScanPointer右移一位,nextToBeChangePointer不变。 // nextToBeScanPointer的向右扫描,直到其等于原数组的最大索引,然后停止。 // nextToBeScanPointer扫描完成后,原数组中所有不等于0的值都已经移动到数组最左边了。 // 注意:然后,别忘了把nextToBeChangePointer指向的位置以及其右侧一直到数组最后一个元素,置为0。 // (因为nextToBeScanPointer只是对原数组进行扫描, // 所以nextToBeChangePointer指向的位置以及其右侧一直到数组最后一个元素,可能为0,可能不等于0, // 需要判断,若不等于0,就置为0) int nextToBeChangePointer = 0; int nextToBeScanPointer = 0; int length = nums.length; while (nextToBeScanPointer < length) { if (nums[nextToBeScanPointer] != 0) { nums[nextToBeChangePointer] = nums[nextToBeScanPointer]; nextToBeChangePointer++; } nextToBeScanPointer++; } while (nextToBeChangePointer < length) { if (nums[nextToBeChangePointer] != 0) { nums[nextToBeChangePointer] = 0; } nextToBeChangePointer++; } } }