使用BufferedReader读取控制台输入

java 复制代码
// 使用BufferedReader从控制台读取字符
import java.io.*;

class BRRead {
    public static void main(String args[]) throws IOException {
        char c;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 创建缓冲读取器 
        System.out.println("Enter characters, 'q' to quit.");
        // 读取字符直到输入'q'
        do {
            c = (char) br.read(); // 读取单个字符 
            System.out.println(c);
        } while (c != 'q');
    }
}
java 复制代码
// 使用BufferedReader从控制台读取字符串import java.io.*;

class BRReadLines {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 包装System.in 
        String str;
        System.out.println("Enter lines of text.");
        System.out.println("Enter 'stop' to quit.");
        do {
            str = br.readLine(); // 读取整行字符串 
            System.out.println(str);
        } while (!str.equals("stop"));
    }
}
java 复制代码
// 简易文本编辑器:读取多行文本并存储
import java.io.*;

class TinyEdit {
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str[] = new String[100]; // 存储最多100行
        System.out.println("Enter lines of text.");
        System.out.println("Enter 'stop' to quit.");
        for (int i = 0; i < 100; i++) {
            str[i] = br.readLine();
            if (str[i].equals("stop")) break; // 输入"stop"时终止        }
        System.out.println("
Here is your file:");
        // 显示存储的文本行 for (int i = 0; i < 100; i++) {
            if (str[i].equals("stop")) break;
            System.out.println(str[i]);
        }
    }
}
java 复制代码
// 演示System.out.write()方法:输出单个字节
class WriteDemo {
    public static void main(String args[]) {
        int b;
        b = 'A';
        System.out.write(b); // 输出字符'A'的ASCII码 
        System.out.write('
'); // 输出换行符
 System.out.flush(); // 建议添加以确保输出 }
}
java 复制代码
// 演示PrintWriter:格式化输出到控制台
import java.io.*;

public class PrintWriterDemo {
    public static void main(String args[]) {
        PrintWriter pw = new PrintWriter(System.out, true); // autoFlush=true 
        pw.println("This is a string");
        int i = -7;
        pw.println(i); // 自动转换为字符串输出 double d = 4.5e-7;
        pw.println(d); // 输出科学计数法数值 }
}
java 复制代码
// 显示文本文件内容(基本版本)
import java.io.*;

class ShowFile {
    public static void main(String args[]) {
        int i;
        FileInputStream fin;
        // 检查命令行参数 if (args.length != 1) {
            System.out.println("Usage: ShowFile filename");
            return; // 提前退出 
        }
        // 尝试打开文件 try {
            fin = new FileInputStream(args[0]); // 创建文件输入流 
        } catch (FileNotFoundException e) {
            System.out.println("Cannot Open File");
            return;
        }
        // 读取文件内容 try {
            do {
                i = fin.read(); // 读取一个字节 
                if (i != -1) System.out.print((char) i); // 转换为字符输出
            } while (i != -1); // -1表示EOF } catch (IOException e) {
            System.out.println("Error Reading File");
        }
        // 关闭文件
        try {
            fin.close();
        } catch (IOException e) {
            System.out.println("Error Closing File");
        }
    }
}
java 复制代码
// 显示文本文件内容(改进版本:使用单个try块和finally)
import java.io.*;

class ShowFile {
    public static void main(String args[]) {
        int i;
        FileInputStream fin = null; // 声明为null        if (args.length != 1) {
            System.out.println("Usage: ShowFile filename");
            return;
        }
        try {
            fin = new FileInputStream(args[0]);
            do {
                i = fin.read();
                if (i != -1) System.out.print((char) i);
            } while (i != -1);
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found.");
        } catch (IOException e) {
            System.out.println("An I/O Error Occurred");
        } finally {
            //确保文件被关闭 try {
                if (fin != null) fin.close(); // 避免NullPointerException            } catch (IOException e) {
                System.out.println("Error Closing File");
            }
        }
    }
}
java 复制代码
// 复制文本文件
import java.io.*;

class CopyFile {
    public static void main(String args[]) throws IOException {
        int i;
        FileInputStream fin = null;
        FileOutputStream fout = null;
        if (args.length != 2) {
            System.out.println("Usage: CopyFile from to");
            return;
        }
        // 复制文件
        try {
            fin = new FileInputStream(args[0]); // 源文件 fout = new FileOutputStream(args[1]); // 目标文件 do {
                i = fin.read();
                if (i != -1) fout.write(i); // 写入目标文件
            } while (i != -1);
        } catch (IOException e) {
            System.out.println("I/O Error: " + e);
        } finally {
            // 分别关闭两个流
            try {
                if (fin != null) fin.close();
            } catch (IOException e2) {
                System.out.println("Error Closing Input File");
            }
            try {
                if (fout != null) fout.close();
            } catch (IOException e2) {
                System.out.println("Error Closing Output File");
            }
        }
    }
}
java 复制代码
// 使用try-with-resources自动关闭文件(Java 7+)
import java.io.*;

class ShowFile {
    public static void main(String args[]) {
        int i;
        if (args.length != 1) {
            System.out.println("Usage: ShowFile filename");
            return;
        }
        // try-with-resources自动管理资源
        try (FileInputStream fin = new FileInputStream(args[0])) { // 自动关闭 
            do {
                i = fin.read();
                if (i != -1) System.out.print((char) i);
            } while (i != -1);
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found.");
        } catch (IOException e) {
            System.out.println("An I/O Error Occurred");
        }
    }
}
java 复制代码
// 使用try-with-resources复制文件(管理多个资源)
import java.io.*;

class CopyFile {
    public static void main(String args[]) throws IOException {
        int i;
        if (args.length != 2) {
            System.out.println("Usage: CopyFile from to");
            return;
        }
        // 单个try语句管理两个资源
        try (FileInputStream fin = new FileInputStream(args[0]);
             FileOutputStream fout = new FileOutputStream(args[1])) {
            do {
                i = fin.read();
                if (i != -1) fout.write(i);
            } while (i != -1);
        } catch (IOException e) {
            System.out.println("I/O Error: " + e);
        }
    }
}
java 复制代码
//演示instanceof运算符:类型检查
class A { int i, j; }
class B { int i, j; }
class C extends A { int k; }
class D extends A { int k; }

class InstanceOf {
    public static void main(String args[]) {
        A a = new A();
        B b = new B();
        C c = new C();
        D d = new D();
 // 基本类型检查
        if (a instanceof A) System.out.println("a is instance of A");
        if (c instanceof A) System.out.println("c can be cast to A"); // 子类实例 if (a instanceof C) System.out.println("a can be cast to C"); // 不会执行
        
        // 多态情况下的类型检查
        A ob;
        ob = d;
        System.out.println("ob now refers to d");
        if (ob instanceof D) System.out.println("ob is instance of D"); // 实际类型为D
        
        ob = c;
        System.out.println("ob now refers to c");
        if (ob instanceof D) System.out.println("ob can be cast to D");
        else System.out.println("ob cannot be cast to D"); // 实际类型为C
        
        // 所有对象都是Object的实例
        if (a instanceof Object) System.out.println("a may be cast to Object");
        if (b instanceof Object) System.out.println("b may be cast to Object");
    }
}
java 复制代码
// 演示assert断言(需启用-ea参数)
class AssertDemo {
    static int val = 3;
    
    static int getnum() {
        return val--;
    }
 public static void main(String args[]) {
        int n;
        for (int i = 0; i < 10; i++) {
            n = getnum();
            assert n > 0; // 断言n>0,当n=0时失败 
            System.out.println("n is " + n);
        }
    }
}
java 复制代码
// 错误使用assert的示例(副作用)
class AssertDemo {
    static int val = 3;
 static int getnum() {
        return val--;
    }
 public static void main(String args[]) {
        int n = 0;
        for (int i = 0; i < 10; i++) {
            // 错误:assert包含赋值操作,禁用断言时n不会被赋值
            assert (n = getnum()) > 0; // 不良实践 
            System.out.println("n is " + n);
        }
    }
}
java 复制代码
// 计算直角三角形斜边(使用Math类静态方法)
class Hypot {
    public static void main(String args[]) {
        double side1 = 3.0;
        double side2 = 4.0;
        // 必须通过类名调用静态方法
        double hypot = Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2)); // sqrt和pow 
        System.out.println("Given sides of lengths " + side1 + " and " + side2 + 
                         " the hypotenuse is " + hypot);
    }
}
java 复制代码
// 使用静态导入简化Math方法调用
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;

class Hypot {
    public static void main(String args[]) {
        double side1 = 3.0;
        double side2 = 4.0;
        // 直接调用静态方法,无需类名
        double hypot = sqrt(pow(side1, 2) + pow(side2, 2)); // 简化调用 
        System.out.println("Given sides of lengths " + side1 + " and " + side2 + " the hypotenuse is " + hypot);
    }
}
java 复制代码
// 构造函数重载(传统方式)
class MyClass {
    int a;
    int b;
 // 分别初始化a和b MyClass(int i, int j) {
        a = i;
        b = j;
    }
    
    // 将a和b初始化为相同值
    MyClass(int i) {
        a = i;
        b = i;
    }
    
    // 默认构造函数:a和b为0
    MyClass() {
        a = 0;
        b = 0;
    }
}
java 复制代码
// 构造函数重载(使用this()调用其他构造函数)
class MyClass {
    int a;
    int b;
 // 主构造函数 MyClass(int i, int j) {
        a = i;
        b = j;
    }
    
    // 调用主构造函数
    MyClass(int i) {
        this(i, i); // 调用MyClass(i, i) 
    }
    
    // 调用单参数构造函数 MyClass() {
        this(0); // 调用MyClass(0) 
    }
}

参考来源

相关推荐
测试开发技术1 小时前
AI 测试提效 | 告别手工写脚本,分享我的 Playwright + Skill 批量生成 UI 自动化脚本方案
自动化测试·人工智能·ui·自动化·agent·skill·ai测试
乐思智能科技有限公司1 小时前
PLECS软件学习使用(二)直流电机基本系统模型
人工智能·算法·机器学习·面试·职场和发展
极连AI1 小时前
极连AI平台解读、Codex5.6仅需0.01倍率,无需Token焦虑,极速响应
人工智能·gpt·chatgpt·aigc·ai编程·ai写作·gpu算力
MartinYeung51 小时前
[论文学习]PACT:溯源感知能力合约——面向智能体安全的参数级溯源
人工智能·学习·安全
带娃的IT创业者2 小时前
Inkling:当开源模型开始思考“如何思考”
人工智能·开源·大语言模型·多模态·moe·开源模型·inkling
远航计算机2 小时前
职业技能培训机构如何利用QClaw+Skills做豆包GEO:知识库搭建×内容创作×效果监测的完整实操手册
大数据·人工智能·自动化·aigc·火山引擎
旋生万物2 小时前
电磁力 = 螺旋联络的 90° 旋转?麦克斯韦方程组的几何重构
人工智能·python·算法·机器学习·copilot·世界模型·物理ai
Vince的修炼之路2 小时前
防 Prompt 注入安全技术深度分析
人工智能·安全
Vince的修炼之路2 小时前
RAG 文档处理技术深度分析:PDF 解析、表格提取、OCR 识别全链路
人工智能·架构