2.5 控制台输入与输出
2.5.1 控制台输入
在 Java 中,可以使用 Scanner 类来实现控制台输入。Scanner 类位于 java.util 包中,因此在使用 Scanner 类之前需要先导入该包。
import java.util.Scanner;
使用 Scanner 类实现控制台输入的步骤如下:
- 创建 Scanner 对象,并将控制台输入流作为参数传递给 Scanner 构造方法。
Scanner scanner = new Scanner(System.in);
- 使用 Scanner 对象的相应方法读取控制台输入的数据。
scanner.nextInt();
- 关闭 Scanner 对象。
scanner.close();
1.从控制台输入整数
下面实例是接收用户输入的数据且输出平均值:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入第一个整数:"); int a = scanner.nextInt(); System.out.print("请输入第二个整数:"); int b = scanner.nextInt(); System.out.print("请输入第三个整数:"); int c = scanner.nextInt(); int sum = a + b + c; double average = sum / 3.0; System.out.println("三个整数的平均值为:" + average); scanner.close(); } }
在上述代码中,首先创建了一个 Scanner 对象 scanner,然后使用 scanner.nextInt()方法读取用户输入的整数,并将其赋值给变量 a、b 和 c。接着,计算三个整数的和,并计算平均值,最后使用 System.out.println()方法输出结果。最后,调用 scanner.close()方法关闭 Scanner 对象。
2.从控制台输入浮点数
下面实例是接收用户输入的数据且输出平均值:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入第一个浮点数:"); double a = scanner.nextDouble(); System.out.print("请输入第二个浮点数:"); double b = scanner.nextDouble(); System.out.print("请输入第三个浮点数:"); double c = scanner.nextDouble(); double sum = a + b + c; double average = sum / 3.0; System.out.println("三个浮点数的平均值为:" + average); scanner.close(); } }
在上述代码中,首先创建了一个 Scanner 对象 scanner,然后使用 scanner.nextDouble()方法读取用户输入的浮点数,并将其赋值给变量 a、b 和 c。接着,计算三个浮点数的和,并计算平均值,最后使用 System.out.println()方法输出结果。最后,调用 scanner.close()方法关闭 Scanner 对象。
3.从控制台输入字符串
下面实例是接收用户输入的数据且输出字符串:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入一个字符串:"); String str = scanner.nextLine(); System.out.println("你输入的字符串是:" + str); scanner.close(); } }
上述代码中,首先创建了一个 Scanner 对象 scanner,然后使用 scanner.nextLine()方法读取用户输入的字符串,并将其赋值给变量 str。接着,使用 System.out.println()方法输出结果。最后,调用 scanner.close()方法关闭 Scanner 对象。
4.其它类型数据的输入
除了上述的输入类型,还有其它类型的数据输入,如:nextByte()
, nextShort()
, nextLong()
, nextFloat()
, nextDouble()
等。这些方法的使用方式与 nextDouble()
类似,都是通过创建 Scanner 对象,然后使用相应的方法读取用户输入的数据,并将其赋值给相应的变量。
了解更多输入方式
****5.从文件中读取数据
除了从控制台读取数据,还可以从文件中读取数据。下面实例是读取文件中的数据并输出:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader("data.txt")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
上述代码中,首先创建了一个 BufferedReader 对象 reader,然后使用 reader.readLine()方法读取文件中的每一行数据,并将其输出。最后,调用 reader.close()方法关闭 BufferedReader 对象。
6.从网络中读取数据
除了从文件和网络中读取数据,还可以从网络中读取数据。下面实例是读取网络中的数据并输出:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; public class Main { public static void main(String[] args) { try { URL url = new URL("http://www.example.com"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (Exception e) { e.printStackTrace(); } } }
上述代码中,首先创建了一个 URL 对象 url,然后使用 url.openStream()方法打开网络连接,并创建了一个 BufferedReader 对象 reader。接着,使用 reader.readLine()方法读取网络中的每一行数据,并将其输出。最后,调用 reader.close()方法关闭 BufferedReader 对象。
7.从键盘读取数据
除了从文件和网络中读取数据,还可以从键盘读取数据。下面实例是读取键盘输入的数据并输出:
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入内容:"); String line = reader.readLine(); System.out.println("您输入的内容是:" + line); reader.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码中,首先创建了一个 BufferedReader 对象 reader,然后使用 reader.readLine()方法读取键盘输入的内容,并将其输出。最后,调用 reader.close()方法关闭 BufferedReader 对象。 #### 8.从控制台读取数据 除了从键盘读取数据,还可以从控制台读取数据。下面实例是读取控制台输入的数据并输出: ```java import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入内容:"); String line = reader.readLine(); System.out.println("您输入的内容是:" + line); reader.close(); } catch (Exception e) { e.printStackTrace(); } } }
上述代码中,首先创建了一个 BufferedReader 对象 reader,然后使用 reader.readLine()方法读取控制台输入的内容,并将其输出。最后,调用 reader.close()方法关闭 BufferedReader 对象。
2.5.2 格式化输出
前面我们使用System.out.println()
输出换行,和System.out.print()
输出不换行,但是这两个方法都不能对输出的内容进行格式化。如果需要对输出内容进行格式化,可以使用System.out.printf()
方法。System.out.printf()
方法类似于 C 语言中的 printf()函数,可以按照指定的格式输出数据。下面实例演示了如何使用 printf()方法进行格式化输出:
1.使用 printf()方法
public class Main { public static void main(String[] args) { int num = 10; double pi = 3.14159; String name = "张三"; System.out.printf("整数:%d,浮点数:%f,字符串:%s\n", num, pi, name); } }
上述代码中,使用 printf()方法按照指定的格式输出整数、浮点数和字符串。其中,
- %d 表示输出整数,
- %f 表示输出浮点数,
- %s 表示输出字符串。
2.使用 String.format()方法
在 Java 中,还可以使用 String.format()方法进行格式化输出。String.format()方法可以将格式化的字符串返回,而不是直接输出。下面实例演示了如何使用 String.format()方法进行格式化输出:
public class Main { public static void main(String[] args) { int num = 10; double pi = 3.14159; String name = "张三"; String result = String.format("整数:%d,浮点数:%f,字符串:%s", num, pi, name); System.out.println(result); } }
上述代码中,使用 String.format()方法按照指定的格式输出整数、浮点数和字符串,并将结果保存在 result 变量中,最后输出 result 变量的值。
其它输出:
int num = 10; final double pi = 3.14159; String name = "张三"; System.out.printf("%9.2f\n",pi);//9.2 中9为长度,2为小数位数,`\n`表示换行 System.out.printf("%+9.2f\n",pi);//+ 表示输出的数带正负号 System.out.printf("%+9.2f\n",pi);//+ 表示输出的数带正负号 System.out.printf("%-9.2f\n",pi);//- 表示左对齐 System.out.printf("%+-9.2f\n",pi);//- 表示输出的数带正负号且左对齐
了解更多输出输入方式
### 2.5.3 输出重定向在 Java 中,可以使用 System.setOut()方法将输出重定向到指定的输出流中。下面实例演示了如何将输出重定向到文件中:
import java.io.*; public class Main { public static void main(String[] args) { try { // 创建文件输出流 FileOutputStream fos = new FileOutputStream("output.txt"); // 创建PrintStream对象,将输出重定向到文件输出流 PrintStream ps = new PrintStream(fos); // 将标准输出流重定向到PrintStream对象 System.setOut(ps); // 输出内容到文件 System.out.println("Hello, World!"); // 关闭文件输出流 fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
上述代码中,首先创建一个文件输出流,然后创建一个 PrintStream 对象,将输出重定向到文件输出流。接着,使用 System.setOut()方法将标准输出流重定向到 PrintStream 对象。最后,使用 System.out.println()方法输出内容到文件中。
2.5.4 输入重定向
在 Java 中,可以使用 System.setIn()方法将输入重定向到指定的输入流中。下面实例演示了如何将输入重定向到文件中:
import java.io.*; public class Main { public static void main(String[] args) { try { // 创建文件输入流 FileInputStream fis = new FileInputStream("input.txt"); // 将标准输入流重定向到文件输入流 System.setIn(fis); // 创建Scanner对象,从标准输入流中读取数据 Scanner scanner = new Scanner(System.in); // 读取输入内容 String input = scanner.nextLine(); // 输出读取的内容 System.out.println("输入内容为:" + input); // 关闭文件输入流 fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
上述代码中,首先创建一个文件输入流,然后使用 System.setIn()方法将标准输入流重定向到文件输入流。接着,创建一个 Scanner 对象,从标准输入流中读取数据。最后,输出读取的内容。
2.5.5 管道流
在 Java 中,可以使用 PipedInputStream 和 PipedOutputStream 类来实现管道流。管道流可以在两个线程之间传递数据。下面实例演示了如何使用管道流:
import java.io.*; public class Main { public static void main(String[] args) throws IOException { // 创建管道输入流和管道输出流 PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(pis); // 创建线程1,将数据写入管道输出流 Thread writerThread = new Thread(() -> { try { pos.write("Hello, World!".getBytes()); pos.close(); } catch (IOException e) { e.printStackTrace(); } }); // 创建线程2,从管道输入流中读取数据 Thread readerThread = new Thread(() -> { try { byte[] buffer = new byte[1024]; int length = pis.read(buffer); String message = new String(buffer, 0, length); System.out.println("读取到的数据为:" + message); pis.close(); } catch (IOException e) { e.printStackTrace(); } }); // 启动线程 writerThread.start(); readerThread.start(); } }
在上面的示例中,我们创建了两个线程,一个线程将数据写入管道输出流,另一个线程从管道输入流中读取数据。当管道输出流关闭时,管道输入流也会自动关闭。
2.6 案例:查询银行账户余额
2.6.1 需求分析
输入被查询的客户的姓名,输出该客户的账户余额。
查询条件:输入客户姓名,按照格式要求输出账户余额。
2.6.2 设计思路
- 定义一个类BankOuery,包含一个main方法。
- 在main方法中,使用Scanner类获取用户输入的客户姓名。
- 根据客户姓名,查询账户余额,并输出结果。
2.6.3 代码实现
//PorjectNane: SE_java_EXP_E002 package cn.campsg.java.experiment; import java.util.Scanner; public class BankQuery { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入被查询的客户的姓名:"); String name = scanner.nextLine(); // 根据姓名查询账户余额 float money = 8888f; System.out.printf("尊敬的客户:%s\n您的余额余额为:%.1f\n", name, money); } }
在上面的示例中,我们使用Scanner类获取用户输入的客户姓名,然后调用System.out.printf()
格式化输出帐户姓名和余额,在实际应用中,我们需要根据具体的业务逻辑来实现查询账户余额的功能。
案例扩展
import java.util.Scanner; public class BankAccount { private double balance; public BankAccount(double initialBalance) { this.balance = initialBalance; } public synchronized void deposit(double amount) { balance += amount; System.out.println("存款:" + amount); System.out.println("当前余额:" + balance); } public synchronized void withdraw(double amount) { if (balance >= amount) { balance -= amount; System.out.println("取款:" + amount); System.out.println("当前余额:" + balance); } else { System.out.println("余额不足,无法取款:" + amount); } } public static void main(String[] args) { BankAccount account = new BankAccount(1000); Scanner scanner = new Scanner(System.in); while (true) { System.out.println("请选择操作:1.存款 2.取款 3.退出"); int choice = scanner.nextInt(); switch (choice) { case 1: System.out.println("请输入存款金额:"); double depositAmount = scanner.nextDouble(); account.deposit(depositAmount); break; case 2: System.out.println("请输入取款金额:"); double withdrawAmount = scanner.nextDouble(); account.withdraw(withdrawAmount); break; case 3: System.exit(0); break; default: } } } }
在这个例子中,我们创建了一个名为BankAccount
的类,它有一个balance
属性和一个deposit
方法。deposit
方法用于存款,它接受一个参数amount
,表示存款金额。如果存款金额大于0,则将金额加到balance
属性上,并打印存款成功的信息;否则,打印存款失败的信息。
在main
方法中,我们创建了一个BankAccount
对象account
,并使用Scanner
类从控制台读取用户输入。根据用户的选择,我们调用account
对象的deposit
方法进行存款操作,或者调用account
对象的withdraw
方法进行取款操作。如果用户选择退出,则使用System.exit(0)
方法退出程序。
import java.util.Scanner; public class BankAccount { private double balance; public void deposit(double amount) { if (amount > 0) { balance += amount; System.out.println("存款成功,当前余额为:" + balance); } else { System.out.println("存款失败,存款金额必须大于0"); } } public static void main(String[] args) { BankAccount account = new BankAccount(); Scanner scanner = new Scanner(System.in); while (true) { System.out.println("请选择操作:1.存款 2.取款 3.退出"); int choice = scanner.nextInt(); switch (choice) { case 1: System.out.println("请输入存款金额:"); double depositAmount = scanner.nextDouble(); account.deposit(depositAmount); break; case 2: System.out.println("请输入取款金额:"); double withdrawAmount = scanner.nextDouble(); account.withdraw(withdrawAmount); break; case 3: System.exit(0); break; default: } } } }
2. 编写一个Java程序,实现一个简单的计算器,可以进行加、减、乘、除运算。要求用户输入两个数字和一个运算符,然后输出运算结果。
import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入第一个数字:"); double num1 = scanner.nextDouble(); System.out.println("请输入第二个数字:"); double num2 = scanner.nextDouble(); System.out.println("请输入运算符(+、-、*、/):"); String operator = scanner.next(); double result = 0; switch (operator) { case "+": result = num1 + num2; break; case "-": result = num1 - num2; break; case "*": result = num1 * num2; break; case "/": result = num1 / num2; break; default: System.out.println("无效的运算符"); return; } System.out.println("运算结果为:" + result); } }
3. 编写一个Java程序,实现一个简单的学生管理系统,要求能够添加、删除、修改和查询学生信息。学生信息包括姓名、年龄和成绩。
import java.util.ArrayList; import java.util.Scanner; public class StudentManagementSystem { public static void main(String[] args) { } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具