package test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a =sc.nextInt();
String b = sc.nextLine();
System.out.println(a+""+b);
sc.close();
}
}
如图代码,当在控制台输入int型数据后,程序自动运行结束。结果如下图。
原因为:Scanner的nextInt()方法只会读取数值,剩下换行符"\n"还没有读取,而之后的nextLine()会读取"\n"并结束该程序,造成用户未输入便“跳过”nextLine()语句的假象。
在这里,解决方法下图(方法有很多,最为推荐该方法,应养成如题所示习惯):
package test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a =sc.nextLine();
int a2 = Integer.parseInt(a);
String b = sc.nextLine();
System.out.println(a2+""+b);
sc.close();
}
}
先定义成String类型用nextInt()方法接收,再对应包装类方法解析成对应类型,即可。
其它char、booleanr等八个基本数据类型亦如此。
工作中,应当养成在使用Scanner接收基本类型数据时先用String型接收再解析成对应类型的良好习惯!