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();
    }
    }

  • 相关阅读:
    Shader Forge学习
    Unity 编辑器扩展
    DoTween
    游戏AI之群组行为
    Unity与服务区交互数据
    NGUI制作流光效果
    NGUI组件整理总结
    Resharp使用简记
    C#使用LitJson对Json数据解析
    BehaviorDesigner学习
  • 原文地址:https://www.cnblogs.com/lszbk/p/12318431.html
Copyright © 2011-2022 走看看