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())。
注意在next()、nextInt()与nextLine()一起使用时,next()、nextInt()往往会读取部分数据(会留下"\n"或者空格之后的数据)。
————————————————
版权声明:本文为优快云博主「qq_41894210」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/qq_41894210/article/details/79889950