- nextInt() 它只读取int值,并且遇到空格也停止,在读取输入后将光标放在同一行
- nextLine() 读取输入,包括单词之间的空格(即,读取到行尾),读取输入后,将光标定位在下一行
- next() 只读取输入到空格。它不能读两个用空格隔开的单词。另外,在读取输入后将光标放在同一行
举例1
-
Scanner cin = new Scanner(System.in); int str1 = cin.nextInt(); String str2 = cin.nextLine(); System.out.println("end"+str2); System.out.println("end"+str1);
输出结果为:
123
end
end123
证明:nextInt在读取输入后将光标放在同一行
举例2
123 123
end 123
end123
上面同样的代码输入123 123结果
证明:nextInt()遇到空格也停止
举例3
如果想让nextInt()后再继续读取下一行
Scanner cin = new Scanner(System.in);
int str1 = cin.nextInt();
cin.nextLine();
String str2 = cin.nextLine();
System.out.println("end"+str1);
System.out.println("end"+str2);
}
123
123
end123
end123
举例4
Scanner cin = new Scanner(System.in);
String str1=cin.next();
String str2=cin.nextLine();
System.out.println("end"+str1);
System.out.println("end"+str2);
结果:
str str
endstr
end str
next()和nextInt()有点类似,不过前者可以读取字符串,它也是空格停止