Home > OS >  A question about a single-line calculator in java?
A question about a single-line calculator in java?

Time:12-09

so, I was trying to solve a question about creating a single line calculator on code forces that takes the input in just one line as following "1 2" and outputs the answer 3 my code works fine with single digits but when it comes to double digits as the following : "7 54" gives "12" and that indicates that the compiler does not recognize "4" so why is that happening ?

also, I want to note that the accepted format of the calculator on code forces is for example '1 2' not "1 2" that is why I used this line of codeString inputWithSpaces = input.replaceAll(".(?=.)", "$0 "); that separates between the string characters with spaces. I did that because if i wrote "1 2"no spaces this gave me error

import java.util.*;
 
public class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
      
 String input = in.nextLine();
        String inputWithSpaces = input.replaceAll(".(?=.)", "$0 "); // this code gives spaces to string input to be accepted in parseINT
            String sum[] =inputWithSpaces .split(" ");
            /*  i took the whole expression in one single string line then i splitted it and
stored it in an array called sum , then by parseInt i was able to identify the type of each element in the arrays indexes
i couldnot identify the operator as char as i cant convert string into char so , i used char O=operator.charAt(0) to conv the string into
char
 
             */
 
            long num1 = Integer.parseInt(sum[0]);
            String operator = sum[1];
            long num2 = Integer.parseInt(sum[2]);
 
            char O = operator.charAt(0);  
            switch (O) {
                case ' ':
                    System.out.println(num1   num2);
                    break;
                case '-':
                    System.out.println(num1 - num2);
                    break;
                case '*':
                    System.out.println(num1 * num2);
                    break;
                default:
                    System.out.println(num1 / num2);
                    break;
            }
  }
} 

CodePudding user response:

Issue

the compiler does not recognize "4"

Not at all, only your code is a fault sum[2] takes one char, the 5, not 54. If you have given 12 15 it wouldn't have worked at all.


Solution

The minimal change would be the regex \D for non-digit. It would put spaces around the operator

input.replaceAll("\\D", " $0 ")

"15 50"   >>   ["15", " ", "50"]

The best would be to directly split the 3 parts

String input = "15 50";
String[] sum = input.split("(?=\\D)|(?<=\\D)");

long num1 = Integer.parseInt(sum[0]);
String operator = sum[1];
long num2 = Integer.parseInt(sum[2]);

switch (operator.charAt(0)) {
    case ' ' -> System.out.println(num1   num2);
    case '-' -> System.out.println(num1 - num2);
    case '*' -> System.out.println(num1 * num2);
    default -> System.out.println(num1 / num2);
}

CodePudding user response:

You should split before and after non-digits.

Replace:

String inputWithSpaces = input.replaceAll(".(?=.)", "$0 ");
String sum[] =inputWithSpaces .split(" ");

With:

String sum[] = input.split("(?=\\D)|(?<=\\D)");

Regex breakdown:

  • (?=\\D) means "the next character is a non-digit"
  • | is the regex logical OR operator
  • (?<=\\D) means "the preceding character is a non-digit"

CodePudding user response:

I think most people forget that Scanner is meant for parsing mixed input, not just user input.

For example, you could easily verify and parse your input using something like...

String input = "7 54";

Scanner parser = new Scanner(input).useDelimiter("");
if (!parser.hasNextInt()) {
    System.out.println("Expecting int value");
    return;
}
int lhs = parser.nextInt();

if (!parser.hasNext()) {
    System.out.println("Expecting operator");
    return;
}
String operator = parser.next();

if (!parser.hasNextInt()) {
    System.out.println("Expecting int value");
    return;
}
int rhs = parser.nextInt();

System.out.println(lhs   " "   operator   " "   rhs);

Which will output 7 54

  •  Tags:  
  • java
  • Related