先Scanner sc=new Scanner(System.in)再String s=sc.nextLine()和String s=new Scanner(System.in).nextLine()的区别

图片说明图片说明

求大神解释:

Scanner sc=new Scanner(System.in);
int id=sc.nextLine();
(执行不正常)

String s=new Scanner(System.in).nextLine();
(执行正常)

是什么原因

两者其实是没什么区别的,唯一的区别是Scanner sc=new Scanner(System.in);这种方式可以再次用到sc对象,而new Scanner(System.in).nextLine();这种方式是只用一次。然后,int id=sc.nextLine();等同于int id =new Scanner(System.in).nextLine();你会发现两个都报错。改成String id=sc.nextLine();就行了,或者改成int id = sc.nextInt();也行。

首先,输入流的正确用法是第一种,定义一个 scanner 后再调用 nextLine ,因为输入流需要关闭。
其次,之所以不正确是因为你定义了 int id 但是接受 nextLine 得到的是字符串,类型不匹配,编译是通不过的,只能用 nextInt 。

nextLine()接收的是字符串类型,你定义的是int,可以换成sc.nextInt()