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

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

一、变量与数据类型(对比Python/C++特性)

1. 变量声明三要素

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

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

// C++(类似Java,但需分号结尾)  
int age = 25;  
std::string name = "CSDN";  

2. Java八大基本数据类型

类型关键字取值范围内存占用
整型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;

二、运算符与表达式

1. 算术运算符的特殊行为

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

int c = 10 % 3;     // 结果1(取模)  

2. 比较运算符 vs 逻辑运算符

类型运算符示例
比较> < >= <= ==if (age >= 18)
逻辑&& \|\| !if (score > 60 && !cheating)

短路特性

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

三、控制流:条件与循环

1. 条件语句(对比Python缩进 vs Java大括号)

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")  

2. switch-case(JDK12+箭头表达式)

String day = "Monday";  
switch (day) {  
    case "Monday" -> System.out.println("工作日");  
    case "Saturday", "Sunday" -> System.out.println("休息日");  
    default -> System.out.println("无效输入");  
}  

3. 循环结构

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());  
    }  
    

相关文章:

  • 基于大模型的视神经脊髓炎手术全流程风险预测与诊疗方案研究
  • Android双亲委派
  • 模板注入(Twig)
  • 文件上传漏洞
  • 在CentOS系统上安装Conda的详细指南
  • Kubernetes教程(六)Harbor的安装和使用
  • 用DeepSeek学Android开发:Android初学者遇到的常见问题有哪些?如何解决?
  • react脚手架(creat-react-app)
  • FreeRTOS 任务间通信机制:队列、信号量、事件标志组详解与实验
  • RabbitMQ 高级特性:从 TTL 到消息分发的全面解析 (下)
  • Spring Boot静态资源访问顺序
  • redis有哪几种持久化方式
  • 通过数据库网格架构构建现代分布式数据系统
  • 顺序表与链表·续
  • Xshell链接Linux机器更换jdk版本
  • 基于架构的软件开发(ABSD)
  • C++11新特性1.原始字面量
  • 学之思社区版考试系统docker-compose部署
  • Selenium 中 ActionChains 支持的鼠标和键盘操作设置及最佳实践
  • Java入门:环境搭建与第一个HelloWorld程序
  • 聊城做网站优化/长沙网站推广
  • 无限动力网站/面点培训学校哪里有
  • 海阳网站建设/企业网站建设的基本流程
  • 微网站开发框架/廊坊百度快照优化
  • 无锡锡山区建设局网站/没有限制的国外搜索引擎
  • 做网站哪些方面会侵权/seo是什么服