Math string with no spaces?

2019-09-02 09:58发布

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.");
        }
    }
}
*/

What I want the program to do is ask one to enter a math operation 1/2 or 1%2 (not multiplication) , but just like that without spaces. Still, I want to check which operation is being done which is why i put the if statements. What I don't get is how the program would know when an operation appears in a string. I'm not even sure if I set it correctly. Overall, I want a string that reads the number then the operation an then the number again. I'm sorry if this seems like doing my hw, but I have tried making this program multiple times, but can't understand how I can do this with a string. I wrote the second one to show that I have done this multiple times, so you can ignore it. Thank You very much!

4条回答
Juvenile、少年°
2楼-- · 2019-09-02 10:15

read input as a String using:

String inputString = input.nextLine();

get the index of the operator:

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 %

get the first and second operand with:

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

get the operator from the indexOp we got earlier:

char operator = inputString.charAt(indexOp);

Hope it helps :)

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-09-02 10:18

Try this:

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!");
            }
    }
}
查看更多
你好瞎i
4楼-- · 2019-09-02 10:25

I have no doubt there are a number of ways this might be achieved, this is simply another example...

What this tries to do, is break down the incoming text into groups of digits and non digits. It then loops through these groups making up the various elements of the calculation...

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

What this does have, is the power to to allow you to supply a much longer calculation, for example 20+30/40-50...etc.

You would need to park each operand and exponent into some kind of List and extract them as you need them...or you could actually do the calculation directly within the while loop

查看更多
Explosion°爆炸
5楼-- · 2019-09-02 10:29

I would like to add another solution, which removes a lot of the parsing work.

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

sample result

Enter an operation:
2 + 3 * 4
2 + 3 * 4 = 14.0
查看更多
登录 后发表回答