网站标题主关键词,wordpress comment meta query,如何保存网页上的视频,微信管理标签三天急速通关JAVA基础知识#xff1a;Day1 基本语法 0 文章说明1 关键字 Keywords2 注释 Comments2.1 单行注释2.2 多行注释2.3 文档注释 3 数据类型 Data Types3.1 基本数据类型3.2 引用数据类型 4 变量与常量 Variables and Constant5 运算符 Operators6 字符串 String7 输入… 三天急速通关JAVA基础知识Day1 基本语法 0 文章说明1 关键字 Keywords2 注释 Comments2.1 单行注释2.2 多行注释2.3 文档注释 3 数据类型 Data Types3.1 基本数据类型3.2 引用数据类型 4 变量与常量 Variables and Constant5 运算符 Operators6 字符串 String7 输入与输出 Input and Output标准输出System.out 8 流程控制 Control Flow9 大数 Big Numbers10 数组 ArraysFinal 考试 0 文章说明
本文目的是为了建立Java的基础知识体系参考《Core Java, Volume I:Fundamentals》第十二版的第三章目录结构组织内容由本人已学习的java知识为基础kimi与gpt辅助完善。本文所提供的信息和内容仅供参考作者和发布者不保证其准确性和完整性。
1 关键字 Keywords
Java关键字是Java语言的保留字不能作为变量名、方法名、类名等标识符使用。下面列出经典的关键字具体示例本篇不给出
abstractassertbooleanbreakbytecasecatchcharclassconstcontinuedefaultdodoubleelseenumextendsfinalfinallyfloatforgotoifimplementsimportinstanceofintinterfacelongnativenewpackageprivateprotectedpublicreturnshortstaticstrictfpsuperswitchsynchronizedthisthrowthrowstransienttryvoidvolatilewhile
比较陌生的 assert用于断言是一种调试手段检查程序中的某个条件是否为真。如果条件为假会抛出AssertionError异常。 default在switch语句中表示默认情况当没有任何case匹配时执行。在接口中从Java 8开始可以用于定义默认方法为接口提供默认实现。 finally用于异常处理finally块中的代码无论是否捕获到异常都会执行。通常用于资源清理如关闭文件流、数据库连接等。 instanceof用于判断一个对象是否是某个类或其子类的实例返回一个布尔值。常用于类型检查和类型转换。 native用于修饰方法表示该方法是本地方法即方法的实现不在Java代码中而是在其他语言如C或C中实现。通常用于调用底层系统资源或性能敏感的操作。 strictfp用于修饰方法或类表示该方法或类中的浮点运算必须严格遵循IEEE 754标准。这可以确保浮点运算在不同平台上具有相同的精度和结果。 synchronized用于修饰方法或代码块表示该方法或代码块是同步的可以用于实现线程同步防止多个线程同时访问共享资源。 transient用于修饰变量表示该变量在对象序列化时不会被序列化。通常用于表示不需要持久化的临时数据。 volatile用于修饰变量表示该变量的值可能会被多个线程同时访问和修改对变量的读写操作需要保证可见性和禁止指令重排序。通常用于多线程环境中的变量共享。
2 注释 Comments
2.1 单行注释
语法//说明单行注释从//开始直到该行末尾。推荐在被注释语句上方另起一行示例// 这是一个单行注释
int x 10; // 这是变量x的声明和初始化2.2 多行注释
语法/* 和 */说明多行注释从/*开始到*/结束可以跨越多行。示例 /** 这是一个多行注释* 可以包含多行文本* 用于对代码块进行详细说明*/int y 20;2.3 文档注释
语法/** 和 */说明多行注释从/**开始到*/结束通常用于生成API文档。它主要用于类、接口、方法和字段的文档化。文档注释可以被javadoc工具解析生成HTML格式的文档。示例 /*** 这是一个文档注释* 用于生成API文档* param x 输入参数* return 返回值*/public int add(int x, int y) {return x y;}3 数据类型 Data Types
Java的数据类型主要分为两大类基本数据类型和引用数据类型。
3.1 基本数据类型
包括整数类型byte、short、int、long、浮点类型float、double、字符类型char和布尔类型boolean。
类型大小位默认值范围byte80-128 到 127short160-32,768 到 32,767int320-2³¹ 到 2³¹-1long640L-2⁶³ 到 2⁶³-1float320.0f约 ±3.40282347E38Fdouble640.0d约 ±1.79769313486231570E308char16‘\u0000’单个字符支持 Unicode 编码boolean不固定false仅能取值 true 或 false
3.2 引用数据类型
引用数据类型在 Java 中是用于存储对象的内存地址而不是直接存储数据值。引用类型主要包括 类Class、接口Interface、数组Array 和 枚举Enum。它们允许更复杂的数据结构和行为的定义。 类Class 类是创建对象的模板包含属性和方法。对象是类的实例。 class Person {String name;int age;void sayHello() {System.out.println(Hello, my name is name);}
}
// 使用类创建对象
Person person new Person();
person.name Alice;
person.age 25;
person.sayHello(); // 输出: Hello, my name is Alice接口Interface 接口是行为的规范定义了一组抽象方法。实现接口的类必须提供这些方法的具体实现。 interface Animal {void makeSound();
}class Dog implements Animal {public void makeSound() {System.out.println(Woof!);}
}
// 使用接口
Animal dog new Dog();
dog.makeSound(); // 输出: Woof! 数组Array 数组是存储相同类型元素的集合长度固定。 int[] numbers {1, 2, 3, 4, 5};
System.out.println(numbers[2]); // 输出: 3String[] names {Alice, Bob, Charlie};
System.out.println(names[0]); // 输出: Alice 枚举Enum 枚举是一个特殊的类用于定义一组固定的常量。 enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}// 使用枚举
Day today Day.WEDNESDAY;
System.out.println(today); // 输出: WEDNESDAY注解Annotations 注解用于提供元数据可以用于类、方法、字段等。注解可以被编译器、运行时环境或其他工具读取和处理。 public interface MyAnnotation {String value();
}MyAnnotation(Hello)
public class MyClass {
}4 变量与常量 Variables and Constant
根据位置不同分为不同类型的变量与常量有哪些位置呢方法中类中以及类中用static修饰了就这三种情况分别就是局部实例以及类(静态) 变量或常量。
类型说明示例变量存储数据的容器具有类型、名称和值。int age 25;局部变量在方法或代码块中定义的变量只在该方法或代码块中有效。public void myMethod() { int localVar 10; }实例变量在类中定义的变量属于类的实例每个对象都有自己的实例变量。public class Person { String name; int age; }类变量在类中定义的静态变量属于类本身所有对象共享同一个类变量。public class Person { static String species Homo sapiens; }常量值在程序运行期间不会改变的变量通常使用final关键字修饰。final double PI 3.14159;实例常量属于类的实例每个对象都有自己的实例常量。public class Person { final String species Homo sapiens; }类常量属于类本身所有对象共享同一个类常量。public class Person { static final String species Homo sapiens; }
变量和常量中容易出错的点 变量类型不匹配 类型不兼容的赋值将不同类型的变量赋值给一个变量时需要进行显式的类型转换或者使用正确的类型。int a 10;
double b 3.14;
a b; // 错误类型不兼容必须显式转换
a (int) b; // 正确类型转换常量定义 常量初始化常量必须在声明时初始化否则会引发编译错误。final int MAX_VALUE; // 错误常量必须初始化
MAX_VALUE 100; // 错误常量只能赋值一次常量修改 不能修改常量值常量被声明后值不可更改尝试修改常量会引发编译错误。final int MAX_VALUE 100;
MAX_VALUE 200; // 错误常量的值不能被修改常量命名 常量命名规范常量通常应使用全大写字母并使用下划线分隔词。final int MaxValue 100; // 不符合规范应该使用 MAX_VALUE
final int MAX_VALUE 100; // 正确变量作用域 局部变量与全局变量冲突如果局部变量和类字段成员变量同名局部变量会遮蔽类字段。int x 10; // 类字段
public void method() {int x 20; // 局部变量遮蔽类字段System.out.println(x); // 输出 20而不是类字段的 10
}静态变量和实例变量 静态变量与实例变量的混淆静态变量属于类而实例变量属于对象。静态变量应通过类名访问而实例变量应通过对象访问。class MyClass {static int staticVar 5;int instanceVar 10;public static void main(String[] args) {MyClass obj new MyClass();System.out.println(staticVar); // 正确可以直接访问静态变量System.out.println(obj.instanceVar); // 正确通过对象访问实例变量}
}变量的默认值 局部变量未初始化局部变量没有默认值必须初始化后才能使用。成员变量有默认值例如int 类型的成员变量默认为 0。int x; // 错误局部变量没有默认值必须初始化引用类型变量的默认值 引用类型变量默认值为 null引用类型的变量如对象类型默认值为 null如果尝试访问它们的属性或方法会引发 NullPointerException。String str; // 默认值为 null
System.out.println(str.length()); // 错误会抛出 NullPointerException5 运算符 Operators
运算符在 Java 中占据着重要的位置对程序的执行有着很大的帮助。除了常见的加减乘除 还有许多其他类型的运算符。
类别运算符形式说明算术运算符, -, *, /, %用于执行基本的加、减、乘、除和取余运算。, - -自增和自减运算符前缀或后缀形式。赋值运算符|, , -, *, /, %用于给变量赋值可结合算术运算符形成复合赋值。关系运算符, !, , , , 比较两个值的关系返回布尔值 true 或 false。逻辑运算符, ||, !用于布尔逻辑运算逻辑与、逻辑或和逻辑非。位运算符, |, ^, ~位与、位或、位异或、位取反运算符。, , 位移运算符左移、右移和无符号右移。条件运算符? :三元运算符根据条件返回不同的值。类型比较运算符instanceof检查对象是否是某个类的实例。位逻辑赋值运算符, |, ^结合位运算和赋值操作。
容易出错的点
取余运算负数取余时结果的符号与被除数一致。 -5 % 3 的结果是 -2。 复合赋值复合赋值运算符会自动进行类型转换可能导致数据精度丢失。int a 5;
a 2.5; // 等价于 a (int)(a 2.5)结果为 7浮点数比较浮点数计算可能会有精度误差因此直接使用 比较可能不准确。 建议使用 Math.abs(a - b) epsilon 方法进行比较。 短路运算 和 || 是短路运算符可能导致右侧表达式不被执行。boolean result (x 5) (y 2); // 如果 x 5y 不会自增符号扩展在位移运算中 会保留符号位 不保留符号位。int a -8;
System.out.println(a 1); // 结果是 -4
System.out.println(a 1); // 结果是一个正数优先级问题条件运算符 ? : 的优先级较低可能需要加括号以避免误解。int a 10, b 5;
int result a b ? a : b 10; // 实际等价于 a b ? a : (b 10)字符串连接 运算符在连接字符串时可能会误解数值操作。System.out.println(Sum: 5 3); // 输出为 Sum: 53而不是 Sum: 86 字符串 String
在Java中String 是一个非常重要的类用于表示和操作字符串。字符串在Java中是不可变的这意味着一旦创建其内容就不能被修改。 常见方法
方法说明示例返回值concat(String str)连接两个字符串java String s1 Hello; String s2 s1.concat( World); “Hello World” 运算符连接两个字符串java String s1 Hello; String s2 s1 World; “Hello World”equals(Object anObject)比较两个字符串的内容是否相同java String s1 Hello; String s2 Hello; boolean isEqual s1.equals(s2); trueequalsIgnoreCase(String anotherString)比较两个字符串的内容是否相同忽略大小写java String s1 Hello; String s2 hello; boolean isEqual s1.equalsIgnoreCase(s2); true比较两个字符串对象是否是同一个对象java String s1 Hello; String s2 Hello; boolean isSameObject s1 s2; true因为字符串常量池indexOf(int ch)返回指定字符在字符串中第一次出现的索引java String s Hello, World!; int index s.indexOf(o); 4lastIndexOf(int ch)返回指定字符在字符串中最后一次出现的索引java String s Hello, World!; int index s.lastIndexOf(o); 8substring(int beginIndex)返回从指定索引开始到字符串末尾的子字符串java String s Hello, World!; String sub s.substring(7); “World!”substring(int beginIndex, int endIndex)返回从指定开始索引到结束索引的子字符串java String s Hello, World!; String sub s.substring(7, 12); “World”toLowerCase()将字符串转换为小写java String s Hello, World!; String lower s.toLowerCase(); “hello, world!”toUpperCase()将字符串转换为大写java String s Hello, World!; String upper s.toUpperCase(); “HELLO, WORLD!”trim()去除字符串两端的空白字符java String s Hello, World! ; String trimmed s.trim(); “Hello, World!”split(String regex)根据指定的正则表达式分割字符串返回一个字符串数组java String s Hello,World,Java; String[] parts s.split(,); [“Hello”, “World”, “Java”]
一些技巧
字符串比较 错误使用比较字符串内容。String s1 Hello;
String s2 hello;
boolean isEqual s1 s2; // false因为字符串常量池正确做法使用equals方法比较字符串内容。String s1 Hello;
String s2 hello;
boolean isEqual s1.equals(s2); // false字符串不可变性 错误尝试修改字符串内容。String s Hello;
s.concat( World); // s 仍然是 Hello正确做法使用新的变量接收修改后的字符串。String s Hello;
String newS s.concat( World); // newS 是 Hello World字符串常量池 错误假设所有字符串字面量都会进入字符串常量池。String s1 Hello;
String s2 new String(Hello);
boolean isSameObject s1 s2; // false因为s2是通过new创建的正确做法使用intern方法确保字符串进入常量池。String s1 Hello;
String s2 new String(Hello).intern();
boolean isSameObject s1 s2; // true字符串分割 错误忽略分割后的空字符串。String s a,,b,c,,;
String[] parts s.split(,);
// parts 会包含空字符串 [a, , b, c, , ]正确做法使用正则表达式去除空字符串。String s a,,b,c,,;
String[] parts s.split(,);
// parts 不会包含空字符串 [a, b, c]字符串连接 错误在循环中使用连接字符串导致性能问题。String result ;
for (int i 0; i 1000; i) {result result i; // 每次迭代都会创建新的字符串对象
}正确做法使用StringBuilder或StringBuffer进行字符串连接。StringBuilder sb new StringBuilder();
for (int i 0; i 1000; i) {sb.append(i); // 高效的字符串连接
}
String result sb.toString();7 输入与输出 Input and Output
输入和输出I/O是程序与用户或其他系统进行交互的重要方式。Java提供了丰富的类和接口来处理输入和输出操作主要位于java.io包中。下面只介绍基础的输入输出处理
Scanner 类 nextLine()读取一行文本。Scanner scanner new Scanner(System.in);
System.out.print(Enter your name: );
String name scanner.nextLine(); // 读取一行文本nextInt()读取一个整数。System.out.print(Enter your age: );
int age scanner.nextInt(); // 读取一个整数nextDouble()读取一个双精度浮点数。System.out.print(Enter your salary: );
double salary scanner.nextDouble(); // 读取一个双精度浮点数next()读取一个单词以空白字符分隔的字符串。System.out.print(Enter your name: );
String name scanner.next(); // 读取一个单词标准输出System.out
print 方法 print(String s)输出一个字符串不换行。System.out.print(Hello, ); // 输出字符串不换行print(int i)输出一个整数不换行。System.out.print(123); // 输出整数不换行print(double d)输出一个双精度浮点数不换行。System.out.print(3.14); // 输出浮点数不换行printf 方法 printf(String format, Object... args)格式化输出。 System.out.printf(Hello, %s. You are %d years old., John, 30); // 格式化输出易错点 使用Scanner类 确保关闭Scanner对象释放系统资源。捕获InputMismatchException处理输入错误。在使用nextInt()或nextDouble()后调用nextLine()清除缓冲区中的换行符。 使用print和printf方法 确保格式化字符串中的占位符与实际参数类型匹配。使用println方法或手动添加换行符确保输出内容格式正确。使用printf方法时使用%n换行符确保每行输出后换行。
8 流程控制 Control Flow
略
9 大数 Big Numbers
Java提供了BigInteger和BigDecimal类来处理这种大数值超出常规数据类型如int和long范围的数值问题。
BigInteger类任意精度的整数运算
方法说明示例BigInteger(String val)通过字符串创建BigInteger对象BigInteger bigInt1 new BigInteger(123456789012345678901234567890);BigInteger.valueOf(long val)通过长整数值创建BigInteger对象BigInteger bigInt2 BigInteger.valueOf(12345678901234567890L);add(BigInteger val)加法BigInteger sum bigInt1.add(bigInt2);subtract(BigInteger val)减法BigInteger difference bigInt1.subtract(bigInt2);multiply(BigInteger val)乘法BigInteger product bigInt1.multiply(bigInt2);divide(BigInteger val)除法BigInteger quotient bigInt1.divide(bigInt2);mod(BigInteger val)取模BigInteger remainder bigInt1.mod(bigInt2);
BigDecimal类任意精度的浮点数运算
方法说明示例BigDecimal(String val)通过字符串创建BigDecimal对象BigDecimal bigDecimal1 new BigDecimal(12345.67890);BigDecimal.valueOf(double val)通过double值创建BigDecimal对象BigDecimal bigDecimal2 BigDecimal.valueOf(12345.67890);add(BigDecimal val)加法BigDecimal sum bigDecimal1.add(bigDecimal2);subtract(BigDecimal val)减法BigDecimal difference bigDecimal1.subtract(bigDecimal2);multiply(BigDecimal val)乘法BigDecimal product bigDecimal1.multiply(bigDecimal2);divide(BigDecimal val, int scale, RoundingMode mode)除法指定小数位数和舍入模式BigDecimal quotient bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP);
Java中BigInteger和BigDecimal类的常见易错点 BigInteger类 使用错误的构造方法 错误使用BigInteger(int signum, byte[] magnitude)构造方法时传入的参数不正确。byte[] bytes {1, 2, 3};
BigInteger bigInt new BigInteger(1, bytes); // 正确
BigInteger bigInt new BigInteger(-1, bytes); // 负数正确做法确保signum参数正确1表示正数-1表示负数0表示零。byte[] bytes {1, 2, 3};
BigInteger bigInt new BigInteger(1, bytes); // 正确除法运算未处理异常 错误在进行除法运算时未处理ArithmeticException。BigInteger bigInt1 new BigInteger(10);
BigInteger bigInt2 new BigInteger(0);
BigInteger quotient bigInt1.divide(bigInt2); // 抛出ArithmeticException正确做法在进行除法运算时确保除数不为零或捕获ArithmeticException。BigInteger bigInt1 new BigInteger(10);
BigInteger bigInt2 new BigInteger(0);
try {BigInteger quotient bigInt1.divide(bigInt2);
} catch (ArithmeticException e) {System.out.println(除数不能为零);
}使用intValue、longValue等方法时未处理溢出 错误在将BigInteger转换为int或long时未处理可能的溢出。BigInteger bigInt new BigInteger(12345678901234567890);
int value bigInt.intValue(); // 可能溢出正确做法在转换前使用bitLength方法检查数值是否在范围内。BigInteger bigInt new BigInteger(12345678901234567890);
if (bigInt.bitLength() 31) {int value bigInt.intValue();
} else {System.out.println(数值超出int范围);
}BigDecimal类 使用double值创建BigDecimal 错误使用double值创建BigDecimal导致精度问题。BigDecimal bigDecimal new BigDecimal(12345.67890); // 精度问题正确做法使用字符串创建BigDecimal避免精度问题。BigDecimal bigDecimal new BigDecimal(12345.67890); // 正确除法运算未处理异常 错误在进行除法运算时未处理ArithmeticException。BigDecimal bigDecimal1 new BigDecimal(10);
BigDecimal bigDecimal2 new BigDecimal(0);
BigDecimal quotient bigDecimal1.divide(bigDecimal2); // 抛出ArithmeticException正确做法在进行除法运算时确保除数不为零或捕获ArithmeticException。BigDecimal bigDecimal1 new BigDecimal(10);
BigDecimal bigDecimal2 new BigDecimal(0);
try {BigDecimal quotient bigDecimal1.divide(bigDecimal2);
} catch (ArithmeticException e) {System.out.println(除数不能为零);
}除法运算未指定舍入模式 错误在进行除法运算时未指定舍入模式导致ArithmeticException。BigDecimal bigDecimal1 new BigDecimal(10);
BigDecimal bigDecimal2 new BigDecimal(3);
BigDecimal quotient bigDecimal1.divide(bigDecimal2); // 抛出ArithmeticException正确做法在进行除法运算时指定舍入模式。BigDecimal bigDecimal1 new BigDecimal(10);
BigDecimal bigDecimal2 new BigDecimal(3);
BigDecimal quotient bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP); // 正确使用floatValue、doubleValue等方法时未处理精度损失 错误在将BigDecimal转换为float或double时未处理可能的精度损失。BigDecimal bigDecimal new BigDecimal(12345.67890);
double value bigDecimal.doubleValue(); // 精度损失正确做法在转换前确保数值在范围内或使用setScale方法调整精度。BigDecimal bigDecimal new BigDecimal(12345.67890);
BigDecimal scaledValue bigDecimal.setScale(2, RoundingMode.HALF_UP);
double value scaledValue.doubleValue(); // 正确希望这些信息对你有帮助如果你有任何问题或需要进一步的解释请随时告诉我。
10 数组 Arrays
一维数组
方法说明示例声明数组声明一个数组但不初始化int[] arr;静态初始化在声明数组时直接赋值int[] arr {1, 2, 3, 4, 5};动态初始化指定数组的长度元素默认初始化int[] arr new int[5];
二维数组
方法说明示例声明和初始化二维数组声明并初始化二维数组int[][] matrix {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
常见方法
方法说明示例length获取数组长度int len arr.length;arr[index]访问数组元素int element arr[0];arr[index] value修改数组元素arr[0] 10;Arrays.sort排序数组Arrays.sort(arr);Arrays.binarySearch查找数组元素int index Arrays.binarySearch(arr, 3);Arrays.fill填充数组Arrays.fill(arr, 10);Arrays.copyOf复制数组int[] copy Arrays.copyOf(arr, arr.length);Arrays.asList将数组转换为列表ListInteger list Arrays.asList(arr);Arrays.toString将数组转换为字符串System.out.println(Arrays.toString(arr));Arrays.deepToString将多维数组转换为字符串System.out.println(Arrays.deepToString(matrix));
Final 考试 关键字 模拟一个动物世界支持鸟类和哺乳动物的多态行为并限制某些动物不能被继承或扩展。 interface Animal {void makeSound();void move();
}abstract class Bird implements Animal {protected String name;public Bird(String name) {this.name name;}public abstract void fly();Overridepublic void move() {System.out.println(name is moving.);}
}final class Eagle extends Bird {public Eagle(String name) {super(name);}Overridepublic void makeSound() {System.out.println(name screeches!);}Overridepublic void fly() {System.out.println(name is soaring high.);}
}class Mammal implements Animal {private String name;public Mammal(String name) {this.name name;}Overridepublic void makeSound() {System.out.println(name makes a mammal sound.);}Overridepublic void move() {System.out.println(name is walking.);}
}public class Main {public static void main(String[] args) {Animal eagle new Eagle(Golden Eagle);eagle.makeSound();eagle.move();Animal lion new Mammal(Lion);lion.makeSound();lion.move();}
}注释 为一个贷款利息计算器编写详细的注释解释计算步骤和逻辑。 /*** 贷款利息计算器* 计算贷款的月还款金额和总利息*/
public class LoanCalculator {/*** 计算月还款金额* param principal 贷款本金* param annualRate 年利率小数形式* param months 贷款期数以月为单位* return 每月还款金额*/public double calculateMonthlyPayment(double principal, double annualRate, int months) {double monthlyRate annualRate / 12; // 月利率return (principal * monthlyRate) / (1 - Math.pow(1 monthlyRate, -months));}/*** 计算总利息* param monthlyPayment 每月还款金额* param months 贷款期数* param principal 贷款本金* return 总利息*/public double calculateTotalInterest(double monthlyPayment, int months, double principal) {return (monthlyPayment * months) - principal;}public static void main(String[] args) {LoanCalculator calculator new LoanCalculator();double principal 50000; // 本金double annualRate 0.05; // 年利率int months 24; // 期数double monthlyPayment calculator.calculateMonthlyPayment(principal, annualRate, months);double totalInterest calculator.calculateTotalInterest(monthlyPayment, months, principal);System.out.printf(每月还款金额: %.2f\n, monthlyPayment);System.out.printf(总利息: %.2f\n, totalInterest);}
} 数据类型 模拟一个个人信息管理系统支持用户输入、修改和打印复杂的个人数据。 import java.util.Scanner;public class PersonalInfoManager {public static void main(String[] args) {Scanner scanner new Scanner(System.in);// 基本数据类型System.out.print(请输入姓名: );String name scanner.nextLine();System.out.print(请输入年龄: );int age scanner.nextInt();System.out.print(请输入身高 (米): );float height scanner.nextFloat();System.out.print(是否已婚 (true/false): );boolean isMarried scanner.nextBoolean();// 输出个人信息System.out.println(\n个人信息:);System.out.printf(姓名: %s\n, name);System.out.printf(年龄: %d\n, age);System.out.printf(身高: %.2f 米\n, height);System.out.printf(婚姻状况: %s\n, isMarried ? 已婚 : 未婚);}
} 变量与常量 设计一个动态管理圆的系统可以根据用户输入动态创建多个圆并输出总圆数和每个圆的面积。 class Circle {private static int totalCircles 0; // 类变量private double radius; // 实例变量private static final double PI 3.14159; // 类常量public Circle(double radius) {this.radius radius;totalCircles;}public double calculateArea() {return PI * radius * radius;}public static int getTotalCircles() {return totalCircles;}
}public class CircleManager {public static void main(String[] args) {Circle c1 new Circle(3.5);Circle c2 new Circle(4.2);System.out.printf(圆1的面积: %.2f\n, c1.calculateArea());System.out.printf(圆2的面积: %.2f\n, c2.calculateArea());System.out.println(总圆数: Circle.getTotalCircles());}
} 运算符 public class OperatorsExample {public static void main(String[] args) {int a 15, b 5, c 2;// 使用括号来明确运算优先级int result (a b) * c - (b % c);System.out.println(表达式计算结果: result);// 复合赋值运算符a 5; // a a 5System.out.println(a 经过复合赋值运算后的值: a);// 三目运算符int max (a b) ? a : b;System.out.println(a 和 b 中较大的值: max);// 自增和自减运算符int preIncrement a; // 先加再使用int postDecrement b--; // 先使用再减System.out.println(自增后的 a: preIncrement);System.out.println(自减后的 b: postDecrement);// 逻辑运算符boolean condition (a 20) (b 10);System.out.println(逻辑运算结果 (a 20) (b 10): condition);}
} 字符串 import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class StringExample {public static void main(String[] args) {String str Hello, World! 123 Java;// 字符串拼接String result str - Welcome!;System.out.println(拼接后的字符串: result);// 查找某一子字符串int index str.indexOf(Java);System.out.println(Java 字符串的起始索引: index);// 正则表达式匹配String regex \\d; // 匹配数字Pattern pattern Pattern.compile(regex);Matcher matcher pattern.matcher(str);while (matcher.find()) {System.out.println(找到的数字: matcher.group());}// 字符串替换String replaced str.replace(World, Java);System.out.println(替换后的字符串: replaced);// 字符串分割String[] words str.split( );System.out.println(分割后的数组: );for (String word : words) {System.out.println(word);}// 大小写转换System.out.println(大写字符串: str.toUpperCase());System.out.println(小写字符串: str.toLowerCase());// 字符编码转换byte[] bytes str.getBytes(StandardCharsets.UTF_8);String encodedString new String(bytes, StandardCharsets.UTF_8);System.out.println(编码转换后的字符串: encodedString);}
} 流程控制 实现一个科学计算器支持平方、平方根和阶乘计算。 import java.util.Scanner;public class ScientificCalculator {public static double square(double number) {return number * number;}public static double squareRoot(double number) {if (number 0) {throw new IllegalArgumentException(不能计算负数的平方根);}return Math.sqrt(number);}public static long factorial(int number) {if (number 0) {throw new IllegalArgumentException(不能计算负数的阶乘);}long result 1;for (int i 1; i number; i) {result * i;}return result;}public static void main(String[] args) {Scanner scanner new Scanner(System.in);while (true) {System.out.print(\n选择操作1. 平方 2. 平方根 3. 阶乘 4. 退出\n请输入选项);int choice scanner.nextInt();if (choice 4) {System.out.println(退出程序。);break;}System.out.print(请输入一个数字);double number scanner.nextDouble();switch (choice) {case 1 - System.out.printf(平方结果%.2f\n, square(number));case 2 - System.out.printf(平方根结果%.2f\n, squareRoot(number));case 3 - {int intNumber (int) number;System.out.printf(阶乘结果%d\n, factorial(intNumber));}default - System.out.println(无效选项);}}}
}大数 import java.math.BigInteger;
import java.math.BigDecimal;public class BigNumbersExample {public static void main(String[] args) {// BigInteger 示例BigInteger big1 new BigInteger(9876543210123456789);BigInteger big2 new BigInteger(1234567890987654321);// 大数加法BigInteger sum big1.add(big2);System.out.println(大数加法结果: sum);// 大数乘法BigInteger product big1.multiply(big2);System.out.println(大数乘法结果: product);// BigDecimal 示例 - 处理精度高的小数BigDecimal decimal1 new BigDecimal(0.123456789123456789123456789);BigDecimal decimal2 new BigDecimal(0.987654321987654321987654321);// 小数加法BigDecimal decimalSum decimal1.add(decimal2);System.out.println(大数小数加法结果: decimalSum);// 小数乘法BigDecimal decimalProduct decimal1.multiply(decimal2);System.out.println(大数小数乘法结果: decimalProduct);// 限定小数精度BigDecimal rounded decimalProduct.setScale(10, BigDecimal.ROUND_HALF_UP);System.out.println(四舍五入后的小数: rounded);}
}数组 实现一个成绩管理系统支持存储、更新和计算多个学生的平均成绩。 import java.util.Scanner;public class GradeManager {public static void main(String[] args) {Scanner scanner new Scanner(System.in);System.out.print(请输入学生人数);int numStudents scanner.nextInt();double[] grades new double[numStudents];for (int i 0; i numStudents; i) {System.out.printf(请输入学生 %d 的成绩, i 1);grades[i] scanner.nextDouble();}double sum 0;for (double grade : grades) {sum grade;}double average sum / numStudents;System.out.printf(所有学生的平均成绩为%.2f\n, average);}
}