Scanner usage in Java

Scanner usage in Java

ScannerThe interaction between programs and people can be realized, and users can use the keyboard to input.

Different types of input:

String s=sc.next();  //接受字符串数据
System.out.println(s);

int s1= sc.nextInt();//接受整型数据
System.out.println(s1);

double s2= sc.nextDouble();//接受小数数据
System.out.println(s2);

For example: Enter hello world from the keyboard.

import java.util.Scanner;   //先导入Java.util.Scanner包
public class test {
    
    
    public static void main(String[] args) {
    
    
        //创建一个扫描器对象,用于接收键盘数据
        Scanner  sc=new Scanner(System.in);
        //从键盘接收数据
        String s=sc.next();  //接受字符串数据
        System.out.println(s);
    }
}
hello world
hello

The reason why the above will only output "hello" is because this kind of input will stop accepting spaces, tabs, and carriage returns. Therefore, the data after "hello" will not be accepted. If we want to accept the complete "hello world", we can use nextline()accept.

nextline()It accepts a line, spaces and tabs can be accepted, and it will stop accepting data only when it encounters a carriage return.

import java.util.Scanner;   //先导入Java.util.Scanner包
public class test {
    
    
    public static void main(String[] args) {
    
    
        //创建一个扫描器对象,用于接收键盘数据
        Scanner  sc=new Scanner(System.in);
        //从键盘接收数据
        String s= sc.nextLine();  //接受字符串数据
        System.out.println(s);
    }
}
hello world
hello world

Guess you like

Origin blog.csdn.net/weixin_57038791/article/details/129340685