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

    要从标准输入读取数字,必须将其读取为字符串并将其解析为数字。java.util包中的Scanner类根据模式读取并解析基本类型和字符串中的文本。文本源可以是InputStream,文件,String对象或可读对象。

    可以使用Scanner对象从标准输入System.in中读取原始类型值。以下代码说明了如何使用Scanner类构建一个小型计算器来执行加,减,乘和除。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    mport java.util.Scanner;
     
    public class Calculator {
      public static void main(String[] args) {
        System.out.println("type something like: 1+3");
        Scanner scanner = new Scanner(System.in);
        double n1 = Double.NaN;
        double n2 = Double.NaN;
        String operation = null;
     
        try {
          n1 = scanner.nextDouble();
          operation = scanner.next();
          n2 = scanner.nextDouble();
          double result = calculate(n1, n2, operation);
          System.out.printf("%s %s  %s  = %.2f%n", n1, operation, n2, result);
        }
     
        catch (Exception e) {
          System.out.println("An invalid expression.");
        }
      }
     
      public static double calculate(double op1, double op2, String operation) {
        switch (operation) {
        case "+":
          return op1 + op2;
        case "-":
          return op1 - op2;
        case "*":
          return op1 * op2;
        case "/":
          return op1 / op2;
        }
     
        return Double.NaN;
      }
    }

    点击链接查看详细内容

  • 相关阅读:
    poj 1860 Currency Exchange(最短路径的应用)
    poj 2965 The Pilots Brothers' refrigerator
    zoj 1827 the game of 31 (有限制的博弈论)
    poj 3295 Tautology (构造法)
    poj 1753 Flip Game(枚举)
    poj 2109 (贪心)
    poj 1328(贪心)
    Qt 对单个控件美化
    Qt 4基础
    Bash Shell
  • 原文地址:https://www.cnblogs.com/hane/p/7305895.html
Copyright © 2011-2022 走看看