当前位置: 首页 > news >正文

JavaSE:学习输入输出编写简单的程序

一、打印输出到屏幕

Java提供了三种核心输出方法,适合不同场景:

System.out.println()

  • 打印内容后 自动换行
System.out.println("Welcome"); 
System.out.println("to ISS"); 
// 输出:
// Welcome
// to ISS

System.out.print()

  • 打印内容后 不换行 (光标停留在末尾)
System.out.print("Welcome "); 
System.out.print("to ISS"); 
// 输出:Welcome to ISS

System.out.printf()

  • 格式化输出 (类似C语言的printf
String name = "Alice";
int age = 25;
double height = 1.68;
System.out.printf("Name: %s | Age: %d | Height: %.2f m%n", name, age, height);
// 输出:Name: Alice | Age: 25 | Height: 1.68 m
  • 格式说明符:
    • %s:字符串
    • %d:整数
    • %f:浮点数(%.2f保留两位小数)
    • %n:换行符

二、字符串拼接与转义字符

字符串拼接

+ 连接变量与文本:

double price = 9.99;
System.out.println("Price: $" + price); // 输出:Price: $9.99

转义字符

特殊字符需用反斜杠\转义:

序列作用示例
\n换行"Line1\nLine2"
\t制表符"Name:\tAlice"
\"双引号"He said \"Hi\""
\\反斜杠本身"Path: C:\\Users"

三、数字格式化(DecimalFormat)

精确控制数字显示格式:

import java.text.DecimalFormat;double value = 6543.21;// 示例1:保留1位小数(自动四舍五入)
DecimalFormat df1 = new DecimalFormat("#.#");
System.out.println(df1.format(value)); // 输出:6543.2// 示例2:千位分隔符+两位小数
DecimalFormat df2 = new DecimalFormat("#,##0.00");
System.out.println(df2.format(value)); // 输出:6,543.21// 示例3:固定位数(不足补0)
DecimalFormat df3 = new DecimalFormat("000000.000");
System.out.println(df3.format(42.5)); // 输出:000042.500

符号说明 :

  • #:可选数字位(不显示无效0)
  • 0:强制数字位(不足补0)
  • ,:千位分隔符

四、读取用户输入(Scanner)

通过Scanner类获取键盘输入:

import java.util.Scanner;Scanner scanner = new Scanner(System.in); // 创建Scanner对象System.out.print("Enter your name: ");
String name = scanner.nextLine();        // 读取整行文本System.out.print("Enter your age: ");
int age = scanner.nextInt();             // 读取整数System.out.print("Enter salary: ");
double salary = scanner.nextDouble();    // 读取浮点数scanner.close();                         // 关闭Scanner释放资源System.out.printf("Hello %s! You are %d and earn $%.2f", name, age, salary);

注意事项 :

  • nextLine() 会读取空格和换行,而 nextInt()/nextDouble() 遇到空格即停止
  • 混合输入时,建议先用 nextLine() 读取换行符避免冲突
  • 读取后务必调用 scanner.close()

五、日期时间处理(Java 8+)

import java.time.*;
import java.time.format.DateTimeFormatter;// 获取当前时间
LocalDateTime now = LocalDateTime.now();
System.out.println("原始格式: " + now); // 输出:2025-07-24T23:22:22.123// 自定义格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
String formatted = now.format(formatter);
System.out.println("格式化后: " + formatted); // 输出:24/07/2025 23:22:22

常用类 :

  • LocalDate:仅日期(年月日)
  • LocalTime:仅时间(时分秒)
  • LocalDateTime:日期+时间

六、重点总结

功能核心方法/类使用场景
基础打印System.out.println()快速输出内容并换行
格式化输出System.out.printf()控制数字/字符串对齐和精度
数字格式化DecimalFormat显示千位分隔符/固定小数位
用户输入Scanner + nextXxx()读取键盘输入的各类数据
日期处理LocalDateTime + DateTimeFormatter日期计算和格式化显示

七、练习

Java新手编程练习:掌握基础输入输出


题目1:打印姓名和邮箱

编写程序,按指定格式输出姓名和邮箱:

John Smith  
e0011223@u.nus.edu  
解题代码
public class Exercise1 {  public static void main(String[] args) {  System.out.println("John Smith");  System.out.println("e0011223@u.nus.edu");  }  
}  

解析

  • 使用两个System.out.println()分别打印两行内容
  • println()在输出后自动添加换行符,确保姓名和邮箱分行显示
  • 可直接替换引号内字符串为实际信息

题目2:个性化问候语

编写程序,接收用户输入的姓名,输出问候语:

Good Morning [姓名]
解题代码
import java.util.Scanner;  public class Exercise2 {  public static void main(String[] args) {  Scanner scanner = new Scanner(System.in);  System.out.print("Enter your name: ");  String name = scanner.nextLine();  System.out.println("Good Morning " + name);  scanner.close();  }  
}  

解析

  1. 导入Scanner类处理输入
  2. scanner.nextLine()读取整行文本(包括空格)
  3. 字符串拼接操作"Good Morning " + name组合问候语
  4. 必须调用scanner.close()释放资源

️题目3:整数平方计算

输入一个整数,输出其平方值:

输入:5  
输出:25
解题代码
import java.util.Scanner;  public class Exercise3 {  public static void main(String[] args) {  Scanner scanner = new Scanner(System.in);  System.out.print("Enter an integer: ");  int num = scanner.nextInt();  int square = num * num;  System.out.println("Square: " + square);  scanner.close();  }  
}  

解析

  • nextInt()专用于读取整数输入
  • 使用num * num直接计算平方(比Math.pow()更高效)
  • 整数运算不会产生浮点数精度问题

题目4:浮点数平方计算

输入双精度浮点数,输出其平方值:

输入:2.5  
输出:6.25
解题代码
import java.util.Scanner;  public class Exercise4 {  public static void main(String[] args) {  Scanner scanner = new Scanner(System.in);  System.out.print("Enter a number: ");  double num = scanner.nextDouble();  double square = num * num;  System.out.println("Square: " + square);  scanner.close();  }  
}  

解析

  • nextDouble()读取双精度浮点数
  • 浮点数乘法可能产生精度问题(如0.1 * 0.1 = 0.010000000000000002
  • 商业计算建议使用BigDecimal

题目5:金额格式化

输入双精度数,输出保留两位小数(自动四舍五入):

输入:4.555 → 输出:4.56  
输入:3.232 → 输出:3.23
解题代码
import java.text.DecimalFormat;  
import java.util.Scanner;  public class Exercise5 {  public static void main(String[] args) {  Scanner scanner = new Scanner(System.in);  System.out.print("Enter a number: ");  double num = scanner.nextDouble();  DecimalFormat df = new DecimalFormat("0.00");  String formatted = df.format(num);  System.out.println("Formatted: " + formatted);  scanner.close();  }  
}  

解析

  1. DecimalFormat使用模式字符串控制格式

  2. "0.00"
    

    表示:

    • 至少1位整数(不足补0)
    • 固定2位小数(不足补0,超位四舍五入)
  3. 模式改为"#.##"可隐藏整数部分的无效0

http://www.lryc.cn/news/598167.html

相关文章:

  • 【Unity开发】飞机大战项目实现总结
  • DigitalOcean 一键模型部署,新增支持百度开源大模型ERNIE 4.5 21B
  • Socket编程入门:从IP到端口全解析
  • element-plus 组件 ElMessage、ElLoading 弹框 和加载css 样式展示异常总结
  • SQL基础⑫ | 视图篇
  • 若用dnf下载的nginx和源文件下载的nginx冲突
  • 【学习路线】JavaScript全栈开发攻略:前端到后端的完整征程
  • Baumer工业相机堡盟工业相机如何通过YoloV8深度学习模型实现卫星图像识别(C#代码,UI界面版)
  • 20-ospf技术
  • Java Map.Entry 核心解析
  • IPSec VPN -- 野蛮模式
  • OSPF开放式最短路径优先
  • C# 泛型(泛型方法)
  • Python中常用标准库(时间库、随机库、正则表达式)
  • pytest官方Tutorial所有示例详解(一)
  • 基于Node.js开发的开源博客平台ghost安装和使用
  • MySQL高可用部署
  • 云原生MySQL Operator开发实战(一):Operator基础与CRD设计
  • Spring MVC中常用注解_笔记
  • nuxt更改页面渲染的html,去除自定义属性、
  • 【Word Press进阶】自定义区块的行为与样式
  • go项目实战二
  • Linux应用开发基础知识——进程学习2(exec函数、system函数、popen函数)(三)
  • 数据挖掘顶刊TKDE论文分享│ST-LLM+:面向交通预测的图增强时空大语言模型
  • 第五章 Freertos物联网实战 微信小程序篇
  • 从0开始学习R语言-Day56--空间变系数模型
  • Django基础(八)———数据库外键及表关系
  • Transformer Masked loss原理精讲及其PyTorch逐行实现
  • Kubernetes 集群架构和Pod创建流程
  • 【unity游戏开发入门到精通——组件篇】unity的粒子系统力场 (Particle System Force Field)实现如旋风、吸引力、风吹效果等