使用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) 
    }
}

参考来源

相关推荐
IT_陈寒5 小时前
Redis集群切换主节点时,服务竟然全员掉线
前端·人工智能·后端
打工仔折腾 AI5 小时前
多台服务器日志分散难查?用Promtail+Loki+Grafana搭建集中检索平台
服务器·人工智能·后端·python·性能优化·django·grafana
2601_962203515 小时前
需要本地或私有化部署,又担心硬件和配置成本?快鹭KuWork、OpenOcta、安捷AI、AnythingLLM四款企业级AI智能体办公平台技术对比
人工智能
蜗牛互联网5 小时前
OLMo-core 3的token gerrymandering提醒:MoE路由要按时间窗验收
java·人工智能·wpf
欢喜躲在眉梢里5 小时前
时序数据库选型指南:从大数据架构视角拆解 Apache IoTDB 的适用边界
大数据·人工智能·ai·架构·时序数据库·模型
勤劳X码农5 小时前
2026年抖音AI配音软件怎么选?
人工智能
打不了嗝 ᥬ᭄5 小时前
AI-Agent入门
人工智能·agent
Dawson Zhu5 小时前
Cookbook Agent:拓扑Codebook方法与多Agent通信效率优化
人工智能·语言模型·架构·aigc·agi
打工仔折腾 AI5 小时前
DiPlay 实测:iPhone 绕过硬件盒子直连 BYD 车机的思路拆解
android·人工智能·后端·python·gradle·iphone·ai agent 实战
二川bro5 小时前
AI测试Agent 25个全套Skill,直接搭建完整自动化测试流水线
人工智能