Scanner输入的问题
1、若均接收键盘介入的整型时:【回车键盘入下一行内容时,比较普通且正常,未出现报错等意外】
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("请输入学号:");
int sno = sc.nextInt();
System.out.print("请输入成绩:");
int grade = sc.nextInt();
System.out.println("===============");
System.out.println("[" + sno + "," + grade + "]");
}
输出结果:
2、、若均接收键盘介入的字符串类型时:【回车键盘入下一行内容时,比较普通且正常,未出现报错等意外】
public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.print("请输入姓名:"); String name = sc.nextLine(); System.out.print("请输入性别:"); String sex = sc.nextLine(); System.out.println("==============="); System.out.println("[" + name + "," + sex + "]"); }
3、先整型后字符串时的混合情况【回车键入姓名信息阶段出现问题】
public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.print("请输入学号:"); int sno = sc.nextInt(); System.out.print("请输入姓名:"); String name = sc.nextLine(); System.out.print("请输入性别:"); String sex = sc.nextLine(); System.out.print("请输入成绩:"); int grade = sc.nextInt(); System.out.println("==============="); System.out.println("[" + sno + "," + name + "," + sex + ","+ grade + "]"); }
输出结果:
原因分析:
均为整型时【.nextInt()】,键盘键入的整型结束后,按回车会进入换行,进行下一行内容的输入,故不存在问题
均为字符串或者先整型后字符串时的混合情况时【.nextLine()】,应该清楚的知道回车也是字符串啊,会被误以为是个字符串,导致bug的出现,比如在代码3中
输入性别时直接回车,会出现如下结果,但若是键入第2种正常情况的字符串类型外加回车不会出现问题!!因为输入一串字符后,.nextLine()会吸收尾端这个回车字符,
将其视为结束符,光标会移至下一行!
如何解决上述出现的bug呢?【回车被视为字符串类型,导致姓名输入不了!】
方法1:面对先整型后字符串类型,先接收键盘键入的整型后多写一行代码 sc.nextLine();【作用是接收键入的单一回车换行,这样后续输入字符串类型不会受影响】
public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.print("请输入学号:"); int sno = sc.nextInt(); sc.nextLine(); // 接收回车换行符,便于下一行内容的键入 System.out.print("请输入姓名:"); String name = sc.nextLine(); System.out.print("请输入性别:"); String sex = sc.nextLine(); System.out.print("请输入成绩:"); int grade = sc.nextInt(); System.out.println("==============="); System.out.println("[" + sno + "," + name + "," + sex + ","+ grade + "]"); }
输出结果:
方法2:键盘键入的全用字符串类型接收,需要整型时字符串转换为整型就ok,比如用字符串类型的name变量代替整型接收,再重新转换为整型或者重新赋值覆盖【原来存放的值】
public static void main(String[] args) { // TODO Auto-generated method stub String name = null; Scanner sc = new Scanner(System.in); System.out.print("请输入学号:"); name = sc.nextLine(); int sno = Integer.parseInt(name); System.out.print("请输入姓名:"); name = sc.nextLine(); System.out.print("请输入性别:"); String sex = sc.nextLine(); System.out.print("请输入成绩:"); name = sc.nextLine(); int grade = Integer.parseInt(name); System.out.println("==============="); System.out.println("[" + sno + "," + name + "," + sex + ","+ grade + "]"); }
输出结果: