java中的nextInt()与nextLine()用法

public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("请输入你的姓名:"); String name=sc.nextLine(); System.out.println("请输入你的爱好:"); String favor=sc.nextLine(); System.out.println("请输入你的年龄:"); int age=sc.nextInt(); System.out.println("*****************"); System.out.println("姓名:"+name); System.out.println("年龄:"+age); System.out.println("爱好:"+favor); }

结果为:

请输入你的姓名: 李四 请输入你的爱好: 敲代码 请输入你的年龄: 22 ***************** 姓名:李四 年龄:22

爱好:敲代码

public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("请输入你的年龄:"); int age=sc.nextInt(); System.out.println("请输入你的姓名:"); String name=sc.nextLine(); System.out.println("请输入你的爱好:"); String favor=sc.nextLine(); System.out.println("*****************"); System.out.println("姓名:"+name); System.out.println("年龄:"+age); System.out.println("爱好:"+favor);

}

结果为:

请输入你的年龄: 22 请输入你的姓名:

请输入你的爱好:

代码全部都是一样的,只是一句代码位置不一样(结果就大不同)后面的结果就没有读取出来

如果想要在nextInt()后读取一行,就得在nextInt()之后额外加上sc.nextLine(),代码如下

解决方案:

public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("请输入你的年龄:"); int age=sc.nextInt(); System.out.println("请输入你的姓名:"); sc.nextLine(); String name=sc.nextLine(); System.out.println("请输入你的爱好:");

String favor=sc.nextLine();

sc.nextLine();

System.out.println("*****************"); System.out.println("姓名:"+name); System.out.println("年龄:"+age); System.out.println("爱好:"+favor); }

结果为:

请输入你的年龄: 22 请输入你的姓名: 李四 请输入你的爱好: 敲代码

***************** 姓名:李四 年龄:22

爱好:敲代码

原因:next()只读空格之前的数据,并且cursor指向本行,后面的nextLine()会继续读取前面留下的数据。

    想要读取整行,就是用nextLine()。

    读取数字也可以使用nextLine(),不过需要转换:Integer.parseInt(cin.nextLine())。

经验分享 程序员 微信小程序 职场和发展