【问题标题】:Math string with no spaces?没有空格的数学字符串?
【发布时间】:2013-10-16 04:19:46
【问题描述】:
import java.util.Scanner;

public class Improved {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter a number operaion number: "); 
        int operand1 = Integer.parseInt(input.nextLine());
        char expo1 = input.next().charAt(0);
        int operand2 = Integer.parseInt(input.nextLine());

        System.out.println( operand1 + expo1 + operand2 + "=");

        if ( expo1 == '/'  && operand2 == '0' ){
            System.out.println("Cannot divide by zero"); }
        else
            if (expo1 == '-') {
                System.out.println(operand1-operand2);
            } else 
            if (expo1 == '+') {
                System.out.println(operand1+operand2);
            } else
            if (expo1 == '/') {
                System.out.println(operand1/operand2);
            } else 
            if (expo1 == '%') {
                System.out.println(operand1%operand2);
            }
            else{
                System.out.println(" Error.Invalid operator.");
            }
    }
}

//This bottom works, but I found out that this is not what is supposed to be done with this problem

/*
public class Else {
    public static void main(String[] args) {

        int operand1;
        char exp1;
        int operand2;

        if (args.length != 3 ) {
            System.err.println("*** Program needs 3 arguements***");
            System.err.println("Usage: java Else int1 exp int2");
            System.exit(1);
        }

        operand1 = Integer.parseInt(args[0]);

        exp1 = args[1].charAt(0);

        operand2 = Integer.parseInt(args[2]);


        System.out.print(args[0] + args[1] + args[2] + "=");

        if(exp1 == '-') {
            System.out.println(operand1 - operand2);
        } else 
        if (exp1 == '+') {
            System.out.println(operand1 + operand2);
        } else
        if (exp1 == '/') {
            System.out.println(operand1 / operand2);
        } else 
        if (exp1 == '%') {
            System.out.println(operand1 % operand2);
        }
        else{
            System.out.println(" Error.Invalid operator.");
        }
    }
}
*/

我希望程序做的是要求输入数学运算 1/2 或 1%2(不是乘法) , 但就像没有空格一样。不过,我想检查正在执行哪个操作,这就是我放置 if 语句的原因。我没有得到的是程序如何知道操作何时出现在字符串中。我什至不确定我是否设置正确。总的来说,我想要一个字符串,它先读取数字,然后再读取操作,然后再读取数字。如果这看起来像是在做我的硬件,我很抱歉,但我已经尝试过多次制作这个程序,但不明白我如何用字符串来做到这一点。我写了第二个来表明我已经多次这样做了,所以你可以忽略它。非常感谢!

【问题讨论】:

  • 我认为String text = input.nextLine(); 后跟text = text.replaceAll("\s", ""); 会消除用户输入的文本中的所有空格。您可以使用进一步的正则表达式来分解String,提取您需要的部分或另一个Scanner 来扫描每个元素(nextInt 等...)

标签: java string conditional-statements


【解决方案1】:

使用以下方法将输入作为字符串读取:

String inputString = input.nextLine();

获取操作符的索引:

int indexOp = inputString.indexOf("+");
if(indexOp < 0) indexOp = inputString.indexOf("-"); //cannot find +, so find -
if(indexOp < 0) indexOp = inputString.indexOf("/"); //cannot find -, so find /
if(indexOp < 0) indexOp = inputString.indexOf("%"); //cannot find /, so find %

获取第一个和第二个操作数:

int operand1 = Integer.parseInt(inputString.substring(0,indexOp));
int operand2 = Integer.parseInt(inputString.substring(indexOp+1,inputString.length());

从我们之前得到的 indexOp 中获取操作符:

char operator = inputString.charAt(indexOp);

希望对你有帮助:)

【讨论】:

    【解决方案2】:

    我毫不怀疑有很多方法可以实现这一点,这只是另一个例子......

    它试图做的是将传入的文本分解为数字组和非数字组。然后循环遍历构成计算的各个元素的这些组...

    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number operaion number: ");
    String text = input.nextLine();
    System.out.println("Input = " + text);
    text = text.replaceAll("\\s", "");
    System.out.println("Parse = " + text);
    
    Pattern p = Pattern.compile("\\d+|\\D+");
    Matcher m = p.matcher(text);
    int index = 0;
    int op1 = -1;
    int op2 = -2;
    String exp1 = "";
    while (index < 3 && m.find()) {
        System.out.println(index);
        String part = m.group();
        switch (index) {
            case 0:
                op1 = Integer.parseInt(part);
                break;
            case 2:
                op2 = Integer.parseInt(part);
                break;
            case 1:
                exp1 = part;
                break;
        }
        index++;
    }
    
    System.out.println(op1 + " " + exp1 + " " + op2);
    

    这确实具有允许您提供更长计算的能力,例如20+30/40-50...等。

    您需要将每个操作数和指数放入某种 List 并在需要时提取它们...或者您实际上可以直接在 while 循环中进行计算

    【讨论】:

      【解决方案3】:

      试试这个:

      package week11;
      
      import java.util.Scanner;
      
      public class maths {
          public static void main(String[] args) {
      
              Scanner scanner = new Scanner(System.in);
      
              System.out.println("enter a number "); 
      
      
              int x = scanner.nextInt();
              System.out.println("put +, -, / or * ");
              char expo1 = scanner.next().charAt(0);
              System.out.println("second number please ");
              int y = scanner.nextInt();
      
      
              System.out.println( "Answer is" + ":");
      
              if ( expo1 == '/'  && y == '0' ){
                  System.out.println("cannot be divided by 0"); }
              else
                  if (expo1 == '-') {
                      System.out.println(x-y);
                  } else 
                  if (expo1 == '+') {
                      System.out.println(x+y);
                  } else
                  if (expo1 == '/') {
                      System.out.println(x/y);
                  } else 
                  if (expo1 == '%') {
                      System.out.println(x%y);
                  }
                  else{
                      System.out.println(" Error!");
                  }
          }
      }
      

      【讨论】:

        【解决方案4】:

        我想添加另一个解决方案,它消除了很多解析工作。

        import java.util.Scanner;
        import javax.script.ScriptEngine;
        import javax.script.ScriptEngineManager;
        import javax.script.ScriptException;
        
        class Scratch {
            public static void main(String[] args) throws ScriptException {
                System.out.println("Enter an operation:");
                Scanner input = new Scanner(System.in);
                String operation = input.nextLine();
        
                ScriptEngineManager manager = new ScriptEngineManager();
                ScriptEngine engine = manager.getEngineByName("js");
                Object result = engine.eval(operation);
                System.out.printf("%s = %s%n", operation, result);
            }
        }
        

        样本结果

        Enter an operation:
        2 + 3 * 4
        2 + 3 * 4 = 14.0
        

        【讨论】:

          猜你喜欢
          • 2015-05-14
          • 2018-11-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-14
          • 1970-01-01
          相关资源
          最近更新 更多