Java基本概念之难题笔记
in Java with 0 comment
Read: 565

Java基本概念之难题笔记

in Java with 0 comment

引言

文章记录学习过程中遇到的难题

运算符

Example Ⅰ

        int i = 42;
        String s = (i < 40) ? "life" : (i > 50) ? "universe" : "everything";
        System.out.println(s);

分析

题目可以解析为这样:

      String s = (i < 40) ? "life" : (i > 50) ? "universe" : "everything";

       String s2;
 
        if (i < 40) {
            s2 = "life";
        } else if (i > 50) {
            s2 = "universe";
        } else {
            s2 = "everything";
        }

//A : everything

Example Ⅱ

        int a = 5 ;
        System.out.println("value is " + ((a<5)?10.9:9));

// value is 9.0

分析

如上一题所说:?后面的值必须是相同的数据类型

前一个是10.9 ,那么java会根据运算符的精度类型进行自动类型转换,所以后面的应该为9.0

Example Ⅲ

        int m = 5, n = 5;
        if ((m != 5) && (n++ == 5)) {
        }
        System.out.println("a. " + n);


        m = n = 5;
        if ((m != 5) & (n++ == 6)) {
        }
        System.out.println("b. " + n);


        m = n = 5;
        if ((m == 5) || (n++ == 5)) {
        }
        System.out.println("c. " + n);


        m = n = 5;
        if ((m == 5) | (n++ == 6)) {
        }
        System.out.println("d. " + n);


        int a = 1, b = 2;
        int c = a & b;
        System.out.println("a&b " + c);

//a. 5
//b. 6
//c. 5
//d. 6
//a&b 0

分析

&& || ! 称为逻辑运算符
& | ^ 称为位运算符(布尔逻辑运算符)

对于最后一个:

a0001
b0010
a&b0000

则int c = a&b = 0 ;

Responses