JAVA基础知识疑点

基础疑点:1、this.age---- 通过this.age就可以访问当前实例的字段2、super.-----指本函数以外的,上一级函数的引用。3、格式化输出使用System.out.printf(),通过使用占位符%?:public class Main {public static void main(String[] args) {double d = 3.1415926;System.out.printf("%.2f\n", d); // 显示两位小数3.14System.out.p
摘要由CSDN通过智能技术生成

基础疑点:
1、this.age---- 通过this.age就可以访问当前实例的字段
2、super.-----指本函数以外的,上一级函数的引用。
3、格式化输出使用System.out.printf(),通过使用占位符%?:

public class Main {
   
    public static void main(String[] args) {
   
        double d = 3.1415926;
        System.out.printf("%.2f\n", d); // 显示两位小数3.14
        System.out.printf("%.4f\n", d); // 显示4位小数3.1416
    }
}

注意,由于%表示占位符,因此,连续两个%%表示一个%字符本身。

4、把一个整数格式化成十六进制,并用0补足8位:

public class Main {
   
    public static void main(String[] args) {
   
        int n = 12345000;
        System.out.printf("n=%d, hex=%08x", n, n); // 两个%占位符必须传入两个数
    }
}

运行结果: n=12345000, hex=00bc5ea8

5、输入------和输出相比,Java的输入就要复杂得多。
我们先看一个从控制台读取一个字符串和一个整数的例子:

import java.util.Scanner;

public class Main {
   
    public static void main(String[] args) {
   
        Scanner scanner = new Scanner(System.in); // 创建Scanner对象
        System.out.print("Input your name: "); // 打印提示
        String name = scanner.nextLine(); // 读取一行输入并获取字符串
        System.out.print("Input your age: "); // 打印提示
        int age = scanner.nextInt(); // 读取一行输入并获取整数
        System.out.printf("Hi, %s, you are %d\n", name, age); // 格式化输出
    }
}

要测试输入,我们不能在线运行它,因为输入必须从命令行读取,因此,需要走编译、执行的流程:
$ javac Main.java
$ java Main
Java提供Scanner对象来方便输入,读取对应的类型可以使用:scanner.nextLine() / nextInt() / nextDouble() / …

6、要避免NullPointerException错误,可以利用短路运算符&&:

public class Main {
   
    public static void main(String[] args) {
   
        String s1 = null;
        if (s1 != null && s1.equals("hello")) {
   
            System.out.println("hello");
        }
    }
}

7、引用类型判断内容相等要使用equals(),注意避免NullPointerException。

8、使用switch时,注意case语句并没有花括号{},而且,case语句具有“穿透性”,漏写break将导致意想不到的结果:

public class Main {
   
    public static void main(String[] args) {
   
        String fruit = "apple";
        switch (fruit) {
   
        case "apple":
            System.out.println("Selected apple");
            break;
        case "pear":
            System.out.println("Selected pear");
            break;
        case "mango":
            System.out.println("Selected mango");
            break;
            
        default:
            System.out.println("No fruit selected");
            break;
        }
    }
}

9、从Java 12开始,switch语句升级为更简洁的表达式语法,使用类似模式匹配(Pattern Matching)的方法,保证只有一种路径会被执行,并且不需要break语句:

public class Main {
   
    public static void main(String[] args) {
   
        String fruit = "apple";
        switch (fruit
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值