用户交互Scanner
基本语法:
Scanner s = new Scanner (System.in)
获取输入的字符串
通过 Scanner 类的next()与 nextLine ()方法
在读取前判断是否还有输入的数据
用 hasNext() 与 hasNextLine()
创建一个扫描器对象,用于接收键盘数据
Scanner scanner =new Scanner(System.in)
System.out.println(“使用next方式接受:”)
判断用户有没有输入字符串
if (scanner.hasNext()){
使用next方式接受
string str = scanner.next ()
System.out.println(“输出的内容为:”+str)
凡是属于IO流的类如果不关闭会一直占用资源,要养成良好习惯用完就关掉
scanner.close()
}
(IO流:输入输出流)
(此时观察结果发现,输入的hello word ,只输出了 hello)
于是 接下来 我们将next 换成 nextLine 方法
这种不同的结果,就能发现,next 与next Line两种方法的不同之处
Scanner 进阶
从键盘接收数据
int i = 0
float f =0.0f
System.out.println (“请输入整数:”)
接下来。判断他是否输入了整数
如果…那么
if (scanner.hasNextint()){
i = scanner.nextint()
System.out.printin(“整数数据:” + i)
}else{
System.out.printin(“输入的不是整数数据!”)
}