标签:异常 错误 pac mat 有一个 system.in java stream code
1 package cn.itcast_01;
2 /*
3 Scanner: 用于接收键盘录入数据.
4 录入数据格式:
5 导包,创建对象,调用方法
6
7 System类下有一个静态字段:
8 public static final InputStream in; 标准输入流, 对应键盘输入
9 InputStream is = System.in;
10
11 class Demo
12 {
13 public static final int x = 10;
14 public static final Student s = new Student();
15
16 }
17 int y = Demo.x;
18 Student s = Demo.s;
19
20 构造方法:
21 Scanner(InputStream source)
22
23 */
24
25 import java.util.Scanner;
26 public class ScannerDemo
27 {
28 public static void main(String[] args){
29 //创建对象
30 Scanner s = new Scanner(System.in);
31 int x = s.nextInt();
32 System.out.println("x = " + x);
33 }
34 }
/*
基本格式:
public boolean hasNextXxx(): 判断是否为某事类型的元素
public Xxx nextXxx(): 获取该元素
举例: int 类型
public boolean hasNextInt()
public int nextInt()
注意:
InputMismatchException: 输入不匹配异常
*/
package cn.itcast_02;
import java.util.Scanner;
public class ScannerDemo2
{
public static void main(String[] args){
//创建对象
Scanner sc = new Scanner(System.in);
//输入字符串导致InputMisMatchException;
// int x = sc.nextInt();
// System.out.println("x = " + x);
if(sc.hasNextInt()){
int x = sc.nextInt();
System.out.println("x = " + x);
}else{
System.out.println("你输入错误");
}
}
}
标签:异常 错误 pac mat 有一个 system.in java stream code
原文地址:https://www.cnblogs.com/yu-zhi/p/9527163.html