public class IO {
public static void main(String[] args) throws Throwable {
ScannerTest();
// testScanner1();
// testScanner2(); // testInRead(); // testText();
} /**
* Scanner类中的方法
* 优点一: 可以获取键盘输入的字符串
* 优点二: 有现成的获取int,float等类型数据,非常强大,也非常方便;
* */
public static void ScannerTest(){
Scanner sc = new Scanner(System.in);
System.out.println("ScannerTest, Please Enter Name:");
String name = sc.nextLine(); //读取字符串型输入
System.out.println("ScannerTest, Please Enter Age:");
int age = sc.nextInt(); //读取整型输入
System.out.println("ScannerTest, Please Enter Salary:");
float salary = sc.nextFloat(); //读取float型输入
System.out.println("Your Information is as below:");
System.out.println("Name:" + name +"\n" + "Age:"+age + "\n"+"Salary:"+salary);
} /**
* 注意:看下边两个实例验证我们读入数据的时机
* 有两种方式读入数据:用回车方式分隔数据和用空格分隔数据
* 回车分隔数据时:读入数据的时机是在每次执行scanner.nextInt()时
* 空格分隔数据时:读入数据的时机是在第一次执行scanner.nextInt()时
* 然而,上述规则对读入字符串类型时是无效的,因为空格也算是字符串
* 另外,本类型不支持读取字符
*/
private static void testScanner1() {
Scanner scanner = new Scanner(System.in);
System.out.println("--1--");
int l=scanner.nextInt();
int[] num = new int[l];
System.out.println("--2--");
for(int i = 0; i<l && scanner.hasNext(); i++){
System.out.println("--3--");
num[i] = scanner.nextInt();
}
System.out.println("数组输出:" + Arrays.toString(num));
} private static void testScanner2(){
Scanner s = new Scanner(System.in);
System.out.println("--1--");
while (s.hasNext()) {
System.out.println("--2--");
int a = s.nextInt();
System.out.println("--3--");
int b = s.nextInt();
System.out.println("--4--");
System.out.println("加和:" + (a + b));
}
} /**
* System.in方法:
* 这种方法每次只能读进一个字符,即使接收类型为int型,也不能读两位以上的int类型
* 所以这种方法最合适读取字符类型,如果要读取int/float等类型,会很麻烦。局限性很大
* */
public static void testInRead() throws IOException{
char b = (char)System.in.read();
System.out.println("char类型数b:" + b);
} /**
* InputStreamReader和BufferedReader方法
* 通过输入输出流来读取键盘输入
* 此方法读取字符串功能强大
* 但是如果要编程char/int/float还需要进行强制类型转换
* */
public static void testText() throws Throwable{
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
String str = br.readLine();
System.out.println("str:" + str);
}
}