【问题标题】:How to make a program accept a line of different input-types from terminal in java?java - 如何使程序接受来自java终端的一行不同输入类型?
【发布时间】:2013-10-23 16:43:40
【问题描述】:

我有一个关于我的作业的快速问题。我想制作一种计算器,它将读取用户的输入,使用 if-else-loop 来确定如何处理它,然后打印相应的结果。 因此,如果用户输入:4 * 5,我希望程序检查两个整数,并使用 inChar 检查所需的计算类型,然后使用 if-else-loop 来完成其余的工作(我知道如何编写部分),但我需要一些关于如何编写扫描器句子的帮助,它会检查一行中的不同类型的输入。希望你明白我的意思。

我已经拥有的代码部分:

Scanner input = new Scanner(System.in);
int a,b;
char c;
double sum;

System.out.println("Velkommen til en helt enkel kalkulator!");
System.out.println("Vennligst tast inn regnestykket, paa formen: tall, regneart, tall med mellomrom imellom hver input: ");

    String svar=input.nextLine();


if(c='*'){
    sum=a*b;
}else if(c='/'){
    sum=a/b;
}else if(c='+'){
    sum=a+b;
}else if(c='-'){
    sum=a-b;
}else{
    System.out.println("Regnearten var ikke forstaaelig. Programmet termineres.");
}

【问题讨论】:

  • 用你拥有的扫描仪显示部分代码..
  • 简短而准确的问题会引起更多关注,只是说。

标签: java variables input calculator


【解决方案1】:

逐行读取您的输入,然后使用String.split()Pattern 对其进行解析。要读取行使用ScannerSystem.in 包裹BufferedReader

【讨论】:

    【解决方案2】:

    我爱regular expressions!所以让我们使用一个:(\d+)\s*([*/+-])\s*(\d+)

    分解:

    \d+ = 一位或多位数字

    \s* = "空格" 零次或多次

    [*/+-] = */+- 之一

    括号“捕获”匹配的元素,因此您可以稍后访问它们。在java中,使用Matcher.group(int),如下面的片段所示:

    //Do this only once in your program
    Pattern calcPattern = Pattern.compile("(\\d+)\\s*([*/+-])\\s*(\\d+)");
    
    //Do this in your loop
    Matcher m = calcPattern.matcher(input.nextLine());
    if (m.matches()) {
        a = Integer.parseInt(m.group(1)); //Get the first group (first set of digits)
        c = m.group(2); //Get the second group (operator)
        b = Integer.parseInt(m.group(3)); //Get the third group (second set of digits)
        //do stuff with a, b, and c
    } else {
        System.out.println("Please enter a valid expression!");
    }
    

    随着技能的提高,正则表达式很容易扩展 - 例如,将 (\d+) 替换为 (\d+(?:.?\d+)?) 以接受带小数的数字。在这里使用在线正则表达式测试器:http://rubular.com/r/8VibLUpxqP

    (快速注意:Java 代码中正则表达式中的双反斜杠是必要的,因为您不能在字符串中编写单个反斜杠 - http://docs.oracle.com/javase/tutorial/java/data/characters.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2015-03-24
      • 2013-12-23
      • 1970-01-01
      相关资源
      最近更新 更多