Scanner的使用
(1)在JDK5以后出现的用于键盘录入数据的类。
(2)构造方法:
A:讲解了System.in这个东西。
它其实是标准的输入流,对应于键盘录入
B:构造方法
InputStream is = System.in;
Scanner(InputStream is)
C:常用的格式
Scanner sc = new Scanner(System.in);
(3)基本方法格式:
A:hasNextXxx() 判断是否是某种类型的
B:nextXxx() 返回某种类型的元素
(4)要掌握的两个方法
A:public int nextInt()
B:public String nextLine()
(5)需要注意的小问题
A:同一个Scanner对象,先获取数值,再获取字符串会出现一个小问题。
B:解决方案:
a:重新定义一个Scanner对象
b:把所有的数据都用字符串获取,然后再进行相应的转换
package cn.itcast_03;
import java.util.Scanner;
/*
* 常用的两个方法:
* public int nextInt():获取一个int类型的值
* public String nextLine():获取一个String类型的值
*
* 出现问题了:
* 先获取一个数值,在获取一个字符串,会出现问题。
* 主要原因:就是那个换行符号的问题。
* 如何解决呢?
* A:先获取一个数值后,在创建一个新的键盘录入对象获取字符串。
* B:把所有的数据都先按照字符串获取,然后要什么,你就对应的转换为什么。
*/
public class ScannerDemo {
public static void main(String[] args) {
// 创建对象
Scanner sc = new Scanner(System.in);
// 获取两个int类型的值
// int a = sc.nextInt();
// int b = sc.nextInt();
// System.out.println("a:" + a + ",b:" + b);
// System.out.println("-------------------");
// 获取两个String类型的值
// String s1 = sc.nextLine();
// String s2 = sc.nextLine();
// System.out.println("s1:" + s1 + ",s2:" + s2);
// System.out.println("-------------------");
// 先获取一个字符串,在获取一个int值
// String s1 = sc.nextLine();
// int b = sc.nextInt();
// System.out.println("s1:" + s1 + ",b:" + b);
// System.out.println("-------------------");
// 先获取一个int值,在获取一个字符串
// int a = sc.nextInt();
// String s2 = sc.nextLine();
// System.out.println("a:" + a + ",s2:" + s2);
// System.out.println("-------------------");
int a = sc.nextInt();
Scanner sc2 = new Scanner(System.in);
String s = sc2.nextLine();
System.out.println("a:" + a + ",s:" + s);
}
}