使用nextInt()等接受输入时必须注意换行符的输入

参考http://*.com/questions/19331426/for-loop-does-not-iterate-the-way-i-want

见以下代码:

package com.ljh.corejava;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner; public class NextIntTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in);
List<Student> students = new ArrayList<Student>() ; for(int i = 0 ; i < 3; i++){
Student s = new Student();
System.out.print("Enter name:");
s.name = sc.nextLine();
System.out.print("Enter number:");
s.number = sc.nextInt();
students.add(s);
}
for(Student s : students){
System.out.println(s.name+" : " + s.number);
}
}
} class Student{
//学生名字
String name;
//学号
int number;
}

1、输入如下:

Enter name:ll

Enter number:1

Enter name:Enter number:kk

Exception in thread "main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Unknown Source)

at java.util.Scanner.next(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

at com.ljh.corejava.NextIntTest.main(NextIntTest.java:23)

在nextLine()中读取了第一行ll,但nextInt()只读取了数字1却没有读取换行符,下一个nextLine()会读取换行符,再下一个nextInt()会读取k,因此出现了错误,类型不匹配。

解决方法一:

加一个nextLine()读取换行符,并不做处理。

			Student s = new Student();
System.out.print("Enter name:");
s.name = sc.nextLine();
System.out.print("Enter number:");
s.number = sc.nextInt();
sc.nextLine();
students.add(s);

输出结果:

Enter name:ll

Enter number:1

Enter name:ll

Enter number:1

Enter name:kk

Enter number:2

ll : 1

ll : 1

kk : 2

处理方法二:

使用nextLine()读取int类型后,再用Integer.parseInt()产生数字。

			System.out.print("Enter name:");
s.name = sc.nextLine();
System.out.print("Enter number:");
//解决方法二:
s.number = Integer.parseInt(sc.nextLine());
上一篇:数说风口上的DEX:流动性暴涨300% ,“寿司大厨”吃相难看


下一篇:oracle逗号字符串拼接小工具