Tuesday, August 28, 2018

java - How can I "delimit" an integer from a given string?

I am doing an exercise where I must have a string inputted from the keyboard. The string will be simple arithmetic, such as " 2 + 4 + 6 - 8 + 3 - 7". Yes, the format must be like this. Single spaces in between.



The idea is to take this string and eventually print out the answer to it. So far, this is my code:




public class AddemUp {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 + 137: ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
sc.useDelimiter("\\s*\\+\\s*|\\s*\\-\\s*");
int sum = 0;
int theInt;

Scanner sc1 = new Scanner(s);
sc1.useDelimiter("\\s*\\s*");
String plusOrMinus = sc1.next();
int count = 0;
if(s.startsWith("-"))
{
sum -= sc.nextInt();
}
while(sc.hasNextInt())
{

theInt = sc.nextInt();
if(count == 0)
{
sum += theInt;
}
else if(plusOrMinus.equals("+"))
{
sum += theInt;
}
else

{
sum -= theInt;
}
sc1.next();
count++;
}
System.out.println("Sum is: " + sum);
}
}
}



On line 25, where the "sc1.delimiter" is, I do not know how to have the code skip all of the integers (along with the spaces) and isolate ONLY either the "+" or "-". Once this is achieved, I can simply implement it into the while-loop.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...