Home  >  Article  >  Java  >  How to use Java logic control

How to use Java logic control

王林
王林forward
2023-04-28 15:28:061146browse

    1. Block scope

    First of all, before learning the control structure in depth, you need to understand the concept of block (block).

    Block: Compound statement refers to several simple Java statements enclosed by a pair of braces. Blocks determine the scope of variables. A block can be nested within another block.

    public class TestDemo220425 {
        public static void main(String[] args) {
            int n = 10;
            {
                int k = 20;
                int n = 20;
            }
        }
    }

    In this code, the part enclosed by brackets in our main function is the block. A block can be nested inside another block, but note that in Java, variables with the same name cannot be declared in nested blocks. For example, int n = 20 in the inner block of the above code is wrong. Here we need to distinguish between global variables in C/C. When encountering local variables with the same name, local variables will be used first and global variables will be shielded. This is not allowed in Java (Java has no concept of global variables, this is just an analogy).

    2. Sequential structure

    The sequential structure is relatively simple. It is executed line by line in the order in which the code is written.

    Illustration:

    How to use Java logic control

    3. Branch structure

    Illustration:

    How to use Java logic control

    Note: if /else if is a parallel relationship, unlike if else is an either-or relationship, this is called a multi-branch structure.

    A few points to note about the branch structure:

    1. The expression in the if brackets can only be a Boolean expression. Nothing other than 0 is true, and 0 means false.

    2. We recommend the end-of-line style for coding styles in Java.

    3, the dangling else problem, that is to say, it is best to add parentheses to the if/else statement, so that the code is more readable. If not, when there are multiple if/else statements, else must match the nearest else

    public class TeseDemo220424 {
        public static void main(String[] args) {
            int x = 10;
            int y = 10;
            if (x == 10)
                if (y == 10)
                    System.out.println("aaa");
            else //这个else其实匹配的是if(y == 10)
                System.out.println("bbb");
        }
    }

    switch statement problem (key point)

    public class TeseDemo220424 {
        public static void main(String[] args) {
            int a = 3;
            switch(a){
                default:
                    System.out.println("输入错误!");
                    break;
                case 1:
                    System.out.println(1);
                    break;
                case 2:
                    System.out.println(2);
                    break;
            }
        }
    }

    Note:

    1, no matter where the default position is, as long as there is no match In any case, default will be used directly.

    2. Each case statement and the break statement after the default statement cannot be omitted, otherwise it will be executed through. Unless it is in a specific situation, the break cannot be omitted.

    3. The only keywords in the switch structure are case, break, and continue, which are used in loops. This is a branch structure, so don’t be confused.

    4. The data type in the switch brackets can only be byte, short, int, char, String, enum type, and then the constant after the case matches the switch. (Note that it cannot be long, because integers will be converted to int, but converting long to int will cause a loss of precision).

    5. The constant value after the case cannot be repeated. Each case represents a different situation.

    6. Expressions can be placed in the brackets of switch, but not like if statements. Some more complex expressions can be placed.

    7, switch statements can be nested, but they don’t look good.

    Four, Loops

    Three major loops: while loop, for loop, do while loop (the specific basic definition of the loop will not be introduced, here are just some points to pay attention to)

    4.1, easy error points

    1, several parts of the loop, the definition of loop variables, conditional judgment, loop body, iteration of loop variables. Be sure to pay attention to the iteration of loop variables. If a loop variable does not iterate until it moves in the direction of jumping out of the loop, it may cause an infinite loop.

    2. Do not manipulate loop variables inside the loop. Even if you need to use your loop variable, use a temporary variable to receive its value and then use it.

    3. Don’t use floating point numbers as loop variables easily.

    public class TestDemo220425 {
        public static void main(String[] args) {
            for(double x = 0;x != 10;x += 0.1){
                System.out.println("haha");
            }
        }
    }

    As expected, this code loops endlessly, which is what I mean by using floating point numbers as loop variables. Because when 0.1 is stored, the decimal part cannot be accurately expressed in binary, so every time we add it, it is an approximate value. Then 10 may just be skipped after adding, so the loop continues.

    4.2, break statement

    public class TeseDemo220424 {
        public static void main(String[] args) {
            int i = 1;
            while(i <= 10){
                if(i == 2){
                    break;
                }
                System.out.println("hehe");
                i++;
            }
        }
    }

    Screenshot of program running:

    How to use Java logic control

    The function of the break statement is to jump out of the loop it is in, such as when When i == 2, the while loop will be jumped out, so only one hehe will be output.

    Extended usage of break:

    In Java, there is no goto statement, but because the designer believes that the idea of ​​goto statement is not problematic, it can indeed work under certain specific conditions. It has a very good effect of jumping out of the loop, so the labeled break statement was invented in Java, which can break to the outside of the loop specified by the label. (As long as the tag is a legal identifier)**

    Example:

    public class TestDemo220425 {
        public static void main(String[] args) {
            label1:
            while(true){
                for(int i = 0;i < 10;i++){
                    if(i == 3){
                        break label1;
                    }
                    System.out.println(i);
                }
            }
            System.out.println("已跳出循环!");
        }
    }

    Screenshot of program running:

    How to use Java logic control

    可以看到,到我们利用标签后,可以指定跳出到哪里。如果这里只是用break,不用标签的话,那么break就只会跳出里层的for循环,外面的while还是一个死循环,用了标签之后,当i== 3,就可以直接跳出到while循环的外部。

    4.3,continue语句

    public class TeseDemo220424 {
        public static void main(String[] args) {
            int i = 1;
            while(i <= 10){
                if(i == 2){
                    continue;
                }
                System.out.println("hehe");
                i++;
            }
        }
    }

    程序运行截图:

    How to use Java logic control

    continue语句的作用是结束本轮循环而开始下一次的循环,如上题,当i == 2,所以就会直接跳过后面的语句,也就是i++不会执行了,导致i一直等于2,所以陷入了死循环。当然如果你这里用for循环就不会这样了,因为i++的执行顺序在前面,continue影响不到

    continue扩展用法:

    同样的,在continue里面,也是可以使用标签的,可以指定跳到与标签匹配的循环的首部。

    示例:

    public class TestDemo220425 {
        public static void main(String[] args) {
            label1:
            for(int i = 0;i < 10;i++){
                if(i == 3){
                    continue label1;
                }
                System.out.println(i);
            }
    }

    程序运行截图:

    How to use Java logic control

    五,输入输出

    5.1,输出到控制台

    How to use Java logic control

    利用%结合上面的转换符就可以进行格式化的输出,当然在进行格式化输出的时候,也可以运用一些标志,比如输出的时候带前缀,带正负号等等…

    How to use Java logic control

    5.2,从键盘输入

    public class TeseDemo220424 {
        public static void main(String[] args) {
            Scanner myscanner = new Scanner(System.in);
            System.out.println("请输入年龄");
            int num = myscanner.nextInt();
            System.out.println(num);
            System.out.println("请输入名字");
            String str = myscanner.nextLine();//读入一行
            System.out.println(str);
            System.out.println("请输入专业");
            String str1 = myscanner.next();
            System.out.println(str1);//读入一个字符串,遇到空格停止
        }
    }

    这里就是要注意你的输入与你接收的方法要对应,另外就是当你用了nextLine()来接收一行的时候,要注意它前面有不有用输入的方法,因为你的换行会被当成一行读入到nextLine()里面,这里就类似于C语言里面吃掉缓冲区里面的回车是一个道理。

    程序运行截图:

    How to use Java logic control

    扩展,在用键盘进行输入的时候,我们是能够看到我们自己的输入的,但是在某些情况下,比如输入密码,我们一般是不想让人看到的,所以这里可以运用到Console类。(这里只做简要介绍)

    Console类:访问与当前Java虚拟机关联的基于字符的控制台设备(如果有的话)的方法,也即使从控制台接收输入的方法。

    使用示例:

    import java.io.Console;
    public class TestDemo220425 {
        public static void main(String[] args) {
            Console cons = System.console();
            String username = cons.readLine("User name: ");
            char[] passwd = cons.readPassword("Password:");
        }
    }

    在IDEA下的运行截图:

    How to use Java logic control

    ❌???怎么直接报空指针异常了,寻思着这里也没用到指针吧,感到十分的不解…????????

    后来,度娘告诉我是这样的:在使用IDEA等集成开发环境中,使用Console将全为null,表示Java程序无法获得Console实例,是因为JVM不是在命令行中被调用的,或者输入输出被重定向了。以至于我们只能去控制台下或者linux环境下去运行程序,如下图在控制台下运行:

    How to use Java logic control

    可以看到在控制台下运行正常,并且我们输入的密码是看不到的(这里真的输入了的哦,只是看不到,中国人不骗中国人的!????)

    5.3,循环输入

    public class TeseDemo220424 {
        public static void main(String[] args) {
            Scanner myscanner1 = new Scanner(System.in);
            while(myscanner1.hasNextInt()){
                int age = myscanner1.nextInt();
            }
        }
    }

    hasNextInt():如果此扫描器输入中的下一个标记可以使用nextInt()方法将其解释为默认基数中的int值,则返回true。也即是说只有你下一个输入的是int类型的值才能够进入循环。

    程序运行截图:

    How to use Java logic control

    循环输入的时候可以ctrl + D 进行正常退出

    六,猜数字游戏

    这里主要是介绍Java里面的生成随机数的方法

    所在包:Java.util.random

    import java.util.Random;
    public class TeseDemo220424 {
        public static void main(String[] args) {
    //        生成随机数
            Random random = new Random();
            int rannum = random.nextInt(100);//生成[0,100) 的随机数 其他范围可以通过在后面加上数来进行范围改变,默认左边都是从0开始
            
        }
    }

    对于int rannum = random.nextInt();如果你后面nextInt()中不给值,那么它产生的就是所有有效的整数,包括正数,负数,0

    注意:Random random = new Random(2022); 这里在定义随机数对象的时候是可以传参的,因为生成随机数是以时间戳为参考的,所以当你传入一个数后,他就只会以这个数为标准进行时间戳的计算,进而产生的随机数每次都是一样的。

    其他方法:

    How to use Java logic control

    其他方法主要就是Math.random(),这个产生的是0~1之间的小数,左闭右开。当然这个是没有上面那种产生同一个随机数的用法的。

    The above is the detailed content of How to use Java logic control. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete