zoukankan      html  css  js  c++  java
  • Java Scanner

    Java中有一个类Scanner用于读取用户在命令行输入的信息。

    Scanner类需要导入包java.util.Scanner

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import java.util.Scanner;
     
    public class MyClass {
     
        public static void main(String[] args) {
            // 创建一个scanner对象
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入一些字符");
            // 读取用户输入的字符
            String value = scanner.nextLine();
            System.out.println("您输入的字符是:"+value);
        }
    }

    nextLine()方法读取用户输入字符。Scanner还有其它方法。

    nextBigDecimal()
    nextByte()
    nextShort()
    nextInt()
    nextLong()
    nextFloat()
    nextDouble()
    nextBoolean()
    

    这些方法用于读取不同类型的数据。

    有了Scanner类我们能做些人机交互程序,如猜数游戏:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    import java.util.Scanner;
     
    public class MyClass {
     
        public static void main(String[] args) {
            // 创建一个scanner对象
            Scanner scanner = new Scanner(System.in);
            // 生成一个随机数
            int randomNumber = (int)(Math.random()*10);
            System.out.println("请输入你猜的数");
            // 读取用户输入的数
            int value = scanner.nextInt();
     
            while (value!=randomNumber){
                System.out.println("你输入是"+value+",目标数是:"+randomNumber+",再猜猜!");
                // 重新生成随机数
                randomNumber = (int)(Math.random()*10);
                value = scanner.nextInt();
            }
     
            System.out.println("恭喜你猜对了");
        }
    }
  • 相关阅读:
    UVA 10564 Paths through the Hourglass DP
    HDU 3397 Sequence operation 线段树 成段更新 区间合并
    HDU 3308 LCIS 线段树 单点更新+区间合并
    POJ 3667 Hotel 线段树 区间合并
    UVALive 3942 Remember the Word Tire+DP
    POJ 1703 Find them, Catch them
    UVA 1366 Martian Mining DP
    UVA 1456 Cellular Network 贪心+DP
    UVA 11573 Ocean Currents
    【ACM】hdu_zs1_1003_放大的X _201307271557
  • 原文地址:https://www.cnblogs.com/lsyw/p/11546507.html
Copyright © 2011-2022 走看看