zoukankan      html  css  js  c++  java
  • Java中Scanner类


    基本格式:
    public boolean hasNextXxx():判断是否是某种类型的元素
    public Xxx nextXxx():获取该元素

    举例:用int类型的方法举例
    public boolean hasNextInt()
    public int nextInt()

    注意():
    InputMismatchException:输入的和你想要的不匹配

    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 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,b);
    //System.out.println("---------------------");

    //获取两个String类型的值
    //String a = sc.nextLine();
    //String b = sc.nextLine();
    //System.out.println(a,b);
    //System.out.println("---------------------");

    //获取一个String类型的值,在获取一个int值
    //String a = sc.nextLine();
    //int b = sc.nextInt();
    //System.out.println(a,b);
    //System.out.println("---------------------");

    //先获取一个int值,在获取一个字符串
    //int a = sc.nextInt();
    //String s2 = sc.nextLine();
    //System.out.println(a,s2);

    // A:先获取一个数值后,在创建一个新的键盘录入对象获取字符串。
    // int a = sc.nextInt();

    // scanner sc2 = new Scanner();
    // String s = sc.nextLine();
    }
    }

  • 相关阅读:
    电脑操作记录
    【转】XCode快捷键
    【转】iOS开发入门:Xcode常用快捷键
    【转】Android ProgressDialog的使用2
    【转】Android ProgressDialog的使用
    【转】在VMware中安装OS X Yosemite
    【转】VMware Workstation 11 永久激活码key 非注册机
    【转】Xcode 7 真机调试详细步骤
    【转】Xcode7真机调试iOS应用程序
    【转】iOS开发Xcode7真机调试教程
  • 原文地址:https://www.cnblogs.com/lszbk/p/12318431.html
Copyright © 2011-2022 走看看