Java small demo-read console keyboard information

In JavaSE, especially for beginners who just started learning Java, we often need to read keyboard input information from the console to achieve some interactive effects.

Many people will immediately think of the "System.in.read()" function, but this function has a very bad phenomenon, that is, the returned information must be char, which often needs to be escaped, which is quite troublesome.

Some people will use the IO stream method, but I personally recommend the following methods:

public static void main(String[] args) throws IOException {
        
        
        System.out.println("请输入内容:");
        Scanner scanner = new Scanner(System.in);
        String info = scanner.nextLine();
        System.out.println("输入的内容为:" + info);
    }

The result of the operation is as follows:

请输入内容:
张三今年15
输入的内容为:张三今年15

Later we will give this code some deformation.

The above code, when you enter the information, the program will run and end. In order not to let it end immediately, we can put a loop outside.

public static void main(String[] args) throws IOException {
        
        
        while (true) {
        
        
            System.out.println("请输入内容:");
            Scanner scanner = new Scanner(System.in);
            String info = scanner.nextLine();
            System.out.println("输入的内容为:" + info);
        }

    }

After running:

请输入内容:
你好
输入的内容为:你好
请输入内容:
你是谁?
输入的内容为:你是谁?
请输入内容:

You will find that the program will keep running unless you manually stop the program.

Finally, we also make a modification to the program, so that the program will automatically terminate after receiving the specified instruction.

public static void main(String[] args) throws IOException {
        
        
        while (true) {
        
        
            System.out.println("请输入内容:");
            Scanner scanner = new Scanner(System.in);
            String info = scanner.nextLine();
            if (info.equals("程序STOP")) {
        
        
                break;
            }
            System.out.println("输入的内容为:" + info);
        }

    }

After running:

请输入内容:
你好
输入的内容为:你好
请输入内容:
程序STOP

Guess you like

Origin blog.csdn.net/ISWZY/article/details/127857121