目录

Java核心语法从变量到控制流

Java核心语法:从变量到控制流

// Java(强类型语言,需显式声明类型)  
int age = 25;  
String name = "CSDN";  

// Python(动态类型)  
age = 25  
name = "CSDN"  

// C++(类似Java,但需分号结尾)  
int age = 25;  
std::string name = "CSDN";  
类型关键字取值范围内存占用
整型int-2^31 ~ 2^31-14字节
长整型long-2^63 ~ 2^63-18字节
双精度浮点double±4.9e-324 ~ ±1.8e+3088字节
布尔booleantrue/false1字节

避坑指南

  • 浮点数比较不要用 == (用差值绝对值 < 1e-6
  • long 类型赋值需加 L 后缀: long num = 10000000000L;

int a = 10 / 3;     // 结果3(整数除法)  
double b = 10 / 3.0; // 结果3.333...  

int c = 10 % 3;     // 结果1取模  
类型运算符示例
比较> < >= <= ==if (age >= 18)
逻辑&& || !if (score > 60 && !cheating)

短路特性

  • false && ... 不会执行右侧
  • true || ... 不会执行右侧

Java写法

if (score >= 90) {  
    System.out.println("A");  
} else if (score >= 60) {  
    System.out.println("B");  
} else {  
    System.out.println("C");  
}  

Python写法

if score >= 90:  
    print("A")  
elif score >= 60:  
    print("B")  
else:  
    print("C")  
String day = "Monday";  
switch (day) {  
    case "Monday" -> System.out.println("工作日");  
    case "Saturday", "Sunday" -> System.out.println("休息日");  
    default -> System.out.println("无效输入");  
}  

for循环

// 打印1-10(对比C++的相似性)  
for (int i = 1; i <= 10; i++) {  
    System.out.println(i);  
}  

while循环

int count = 0;  
while (count < 5) {  
    System.out.println("执行第" + (count+1) + "次");  
    count++;  // 必须更新循环变量!  
}  

增强for循环

int[] nums = {1, 2, 3};  
for (int num : nums) {  
    System.out.println(num);  
}  

import java.util.Scanner;  

public class Calculator {  
    public static void main(String[] args) {  
        Scanner scanner = new Scanner(System.in);  
        System.out.print("输入第一个数字:");  
        double num1 = scanner.nextDouble();  

        System.out.print("输入运算符(+ - * /):");  
        char operator = scanner.next().charAt(0);  

        System.out.print("输入第二个数字:");  
        double num2 = scanner.nextDouble();  

        switch (operator) {  
            case '+' -> System.out.println("结果:" + (num1 + num2));  
            case '-' -> System.out.println("结果:" + (num1 - num2));  
            case '*' -> System.out.println("结果:" + (num1 * num2));  
            case '/' -> {  
                if (num2 == 0) System.out.println("错误:除数不能为0!");  
                else System.out.println("结果:" + (num1 / num2));  
            }  
            default -> System.out.println("无效运算符");  
        }  
    }  
}  

  1. 编译错误:找不到符号

    • 检查变量名拼写和作用域(局部变量不能在外部使用)
  2. 逻辑错误:循环不执行

    int i = 10;  
    while (i < 5) {  // 条件永远不满足  
        // 代码不会执行  
    }  
  3. 空指针异常(NPE)预判

    String str = null;  
    if (str != null && !str.isEmpty()) {  // 利用短路特性避免NPE  
        System.out.println(str.length());  
    }