Scanner

发布时间 2023-06-11 21:35:28作者: 姜姜萸
Student5_Test
/*Scanner类
作用就是从键盘接受数据
使用方法
1.导包(java.util.Scanner)
2.创建键盘录入的工具(对象)
3.通过这个对象从键盘录入数据

Scanner 常用构造方法
Scanner(InputStream source)
构造一个新的 Scanner ,产生从指定输入流扫描的值。
构造方法的形参列表
InputStream(类型) source(名)

Scanner sc = new Scanner(System.in);
System是一个类,in是System中的一个静态变量,并且是InputStream类型的,System.in是键盘的意思,这句话的意思就是从键盘录入一个数据
Scanner的两个方法:
hasNextXXX();如果此扫描仪在其输入中有另一个令牌,则返回true。判断输入的类型和要接受的类型是否一致
nextXXX();用来接收数据
//ctrl+Alt+L格式整理快捷鍵
String next() 查找并返回此扫描仪的下一个完整令牌。
String nextLine() 将此扫描仪推进到当前行并返回跳过的输入。
next()和nextLine()的主要区别:
1.next方法不会接收没有意义的字符,只有输入了有意义的字符才以回车结束(以有意义为结束)
2.nextLine方法可以接收没有意义的字符,只要按回车就结束(以行为结束)
改进:
用next去代替nextLine就可以了
*/

import java.util.Scanner;

public class Student5_Test {
public static void main(String[] args) {
/*while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数据:");
if (sc.hasNextInt()) {//判断输入的数据时候是要录入的数据类型
int a = sc.nextInt();
System.out.println("你输入的数据是:" + a);
} else {
System.out.println("输入的数据有误,请重新输入!");
}
}*/

Scanner s1 = new Scanner(System.in);

System.out.println("请输入字符串:");

String next = s1.nextLine();
Scanner s2 = new Scanner(System.in);
System.out.println("请输入整数:");

//String next2 = s2.next();
int next2 = s2.nextInt();
//String next2 = s2.nextLine();
System.out.println("输入的整数是:"+next);
System.out.println("输入的字符串是:"+next2);


//String str = sc2.nextLine();
//System.out.println("输入的字符串是:"+str);
//正常情况下,next和nextLine是没有区别的,但是在输入特殊字符,
// 用next 1.输入空格 Tab,回车之类的都会被忽略,从有意义的字符开始算
//2.next接收的字符串中不包括空格Tab,回车
//3.以回车作为字符串结束接收的标准,必须输入了有意义的字符后回车才会接收
//用next();的运行结果
//请输入字符串:
//jswih ,wso swo
//输入的字符串是:jswih
//------------------------
//nextLine运行结果
//请输入字符串:
//hqug aa
//输入的字符串是:hqug aa
//1.nextLine()方法输入特殊字符都会被接收
//2.只要碰回车就接收
}
}