I'm a newb and I started out trying out some things, so I made a calculator that only required one line. It works when I do it in this format : Int space String space int. EG : 10 + 50. If I don't do spaces like 50+50 the program fails. Is there someway to recognise spaces in Java? Bare in mind that I'm a noob but I find that I did a great job that keeped me motivated. Here's teh code :
package Tests;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your values : ");
int first = input.nextInt();
String character = input.next();
int second = input.nextInt();
int answer = 0;
switch (character) {
case "*":
answer = first * second;
break;
case "/":
answer = first/second;
break;
case "-":
answer = first-second;
break;
case "+":
answer = first+second;
break;
default:
System.out.println("Failed to recognise character");
break;
}
System.out.println("Answer : " + answer);
}
}
Scanner#next
reads the next token from the input string based on whatever delimiter you have set for your Scanner
object when you create it. The default delimiter is whitespace, so when you space out the operands and operator your program processes them correctly. You could set the delimiters for your Scanner as the operators.
Scanner input = new Scanner(System.in);
input.useDelimiter("\+|\-|\*|\\");
and your program will function properly.
There are some convenience methods in Scanner that you're using now (i.e. nextInt()
) but for your purpose you should probably just get the nextLine()
and do some more complex parsing of the expression.
This is probably too much and I wouldn't make this my main focus right now if I were you, but eventually you may want to read up about formal languages and use tooling such as http://www.antlr.org/ for purposes like these.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With