JAVA第十天之Scanner类的方法
1.Scanner类简单方法:
public class MyTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
nextXXX 系列的方法
sc.nextInt();//接收int类型的数据
sc.nextDouble();//接收double类型的数据
sc.nextLine();//接收字符串 可包含有空格
sc.next();//接收任意数据,但是接收字符串时 若字符串之间有空格则只接收部分
sc.hasNextXxx();//判断一个是否是某种类型的元素, 其中Xxx可以是Int, Double,line等,如果要判断的是字符串则可以省略Xxx;
}
2. ①注意事项:当先录入一个其他类型的数,这个时候再去使用nextLine()录入字符串的时候,会发现不需要录入程序就停止了,原因是 输入完第一个数后 按了回车换行 但是这个时候 回车换行默认被录入 nextLine()中
public class MyTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“请输入一个整数”);
int i=sc.nextInt();
System.out.println(i);
System.out.println(“请输入一个字符串”);
String s=sc.nextLine();
System.out.println(s);
}
解决方法:重新new 一个对象再去接收 或者 用next()接收 next()默认会忽略掉回车换行
public class MyTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“请输入一个整数”);
int i=sc.nextInt();
System.out.println(i);
System.out.println(“请输入一个字符串”);
//sc=new Scanner(System.in);
String s=sc.nextLine();
//String s=sc.next();
System.out.println(s);
}
②:注意事项: nextLine()与next()的区别
nextLine(); // 输入的字符串 之间可以带有空格
next();//输入的字符串之间如果有空格则只输入第一个空格前的内容
代码示例:
public class MyTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“请输入一个字符串”);
String s=sc.nextLine();
//String s=sc.next();
System.out.printfln(s);
}
运行结果:
3.Scanner类方法的应用
public class MyTest {
public static void main(String[] args) {
scanner();
}
public static void scanner(){
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数");
if(sc.hasNextInt()){
int i = sc.nextInt();
System.out.println(i);
}else{
System.out.println("你输入的类型不正确,请重新输入");
scanner();
}
}
}