I’m trying to create a calculator that takes a string that can be in 4 different formats:
input: add 1 2 13 5 together
=> 1 + 2 + 13 + 5 = 21
input: add 9 to 10
=> 9 + 10 = 19
input: subtract 5 from 13
=> 13 - 5 = 8
input: bye
=> end program
I’ve set up my code like this:
import java.util.*;
class Calculator {
public static void main(String[] args) {
System.out.println("yes>" )
Scanner zip = new Scanner(System.in);
String input = zip.nextLine();
if (input.equals("bye"))
System.exit(0);
else if (input.substring(0, 1) == "a") //assume first cmd is add
(integer.ParseInt(input.subtring(3, BLANK) //extract first number
My problem is that I don’t know the index of the numbers in the string. I wanted to do it like this:
if (input.substring(0, 3) == “add”) => the next digit will be a number. parse integer.substring(3, BLANK). BLANK should be the index of the space character. then that number needs to be placed into a variable, and the program needs to check for all other integers.
I’m a little confused at how to approach this. What if there are 500 numbers that need to be added (or subtracted?) Is there a way to do this recursively, somehow? This program is supposed to use regular expressions which I’ve read about, but I’m not sure how to implement.
Any help would be really appreciated. Thanks in advance
Use the Scanner created and use the following methods:
hasNext,next(for reading “TO”, “SUBTRACT”, etc),hasNextIntandnextInt(for reading NUM). Nothing should be done withinputonce it is given to the scanner. Make sure to tryhasNextIntbeforehasNext, becausehasNextwill return true if the next word matches an integer 🙂Here are some notes to help with building the parser:
“ADD” NUM1 NUMN+ “TOGETHER”; if first NUM1 followed by another NUMN then this format. Keep reading NUMN until there are no more — can put in an ArrayList for later use or compute and emit output immediately. Then there should be a “TOGETHER” at end.
“ADD” NUM1 “TO” NUM2; only when NUM1 followed by “TO”.
“SUBTRACT” NUM1 “FROM” NUM2
“BYE”
Might start like this:
Happy homeworking.