标签:
1、Scanner类概述
public class ScannerDemo { public static void main(String[] args) { // 创建对象 Scanner sc = new Scanner(System.in); // 获取数据,先判断输入的数据是否与接收的变量的类型匹配 if (sc.hasNextInt()) { int x = sc.nextInt(); System.out.println("x:" + x); } else { System.out.println("你输入的数据有误"); } } }
public class ScannerDemo { public static void main(String[] args) { // 创建对象 Scanner sc = new Scanner(System.in); // 获取两个int类型的值 int a1 = sc.nextInt(); int b1 = sc.nextInt(); System.out.println("a:" + a1 + ",b:" + b1); System.out.println("-------------------"); // 获取两个String类型的值 String s1 = sc.nextLine(); String s2 = sc.nextLine(); System.out.println("s1:" + s1 + ",s2:" + s2); System.out.println("-------------------"); // 先获取一个字符串,在获取一个int值 String s3 = sc.nextLine(); int b2 = sc.nextInt(); System.out.println("s1:" + s3 + ",b:" + b2); System.out.println("-------------------"); // 先获取一个int值,在获取一个字符串,数据获取有误 int a2 = sc.nextInt(); String s4 = sc.nextLine(); System.out.println("a:" + a2 + ",s2:" + s4); System.out.println("-------------------"); //解决方法:定义两个Scanner对象,分别获取两次数据 int a = sc.nextInt(); Scanner sc2 = new Scanner(System.in); String s = sc2.nextLine(); System.out.println("a:" + a + ",s:" + s); } }
标签:
原文地址:http://www.cnblogs.com/yangyquin/p/4934146.html