[Java Basics] About inputting multiple data with scanner

Subject requirements:

Enter your name, gender and age and print

There is no problem writing this way

	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入你的姓名");
		String n = sc.next();
		System.out.print("请输入你的性别");
		String s = sc.next();
		System.out.print("请输入你的年龄");
		int a = sc.nextInt();
		System.out.print(n+s+a);
	}

This is ok

	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入你的姓名、性别和年龄");
		String n = sc.next();
		String s = sc.next();
		int a = sc.nextInt();
		System.out.print(n+s+a);
	}

Only one character can be retrieved at a time, even if it is written with nextLine, but this one can read spaces only

It should be noted that
this type of operation such as calling scanner.next() is Insert picture description herecounted as obtaining data once, and several can be obtained several times.
But the order must be one-to-one correspondence, once the data type is found to be out of comparison, an error will be reported.
For example, if the second one is age, which is of type int, and the input is a string, it cannot be obtained.
I have seen some methods from the Internet. You can also store int in an array of string type, and then take it out when needed to convert the type; or add some judgment statements to extract a certain type from a bunch of data, etc. These will be written when I learn more basic grammar and structure later.

Guess you like

Origin blog.csdn.net/qq_44899247/article/details/107048676