【Java】nextInt()与sc.nextLine()的「使用区别与说明」

sc.next()类同于sc.nextInt(),都是以空格或回车换行作为结束

sc.nextLine()以回车换行作为结束.

例:

package TextBag;

import java.util.Scanner;

public class Scanner_text {
    
    
		public static void main(String[] args) {
    
    
			
			Scanner sc = new Scanner(System.in);

			System.out.print("姓名:");
			String name = sc.next();
			
			System.out.print("梦想:");
			String dream = sc.nextLine();
			
			System.out.println("\n"+name+dream);
			
			sc.close();
		}
}

在这里插入图片描述

在上面的结果中我们可以很轻松的看出来,没有读入梦想就直接将姓名输出了,这就是因为sc.nextLine()以回车换行作为结束.

如果想读入梦想怎么办?

解决:

package TextBag;

import java.util.Scanner;

public class Scanner_text {
    
    
		public static void main(String[] args) {
    
    
			
			Scanner sc = new Scanner(System.in);

			System.out.print("姓名:");
			String name = sc.next();
			
			sc.nextLine();
			
			System.out.print("梦想:");
			String dream = sc.nextLine();
			
			System.out.println("\n"+name+dream);
			
			sc.close();
		}
}

在这里插入图片描述

实际上,我们只加了sc.nextLine();这一行代码,因为sc.nextLine()以回车换行作为结束,所以我们加的这一行代码用于接收读入姓名之后的回车,这样就可以继续向下继续读入了。

猜你喜欢

转载自blog.csdn.net/qq_45696288/article/details/121691990#comments_22724617