Question

So I am doing a project for a class of mine and it involves the use of delimiters and other scanner methods. However I've been doing a lot of research and the book we have does not clearly explain as to how it works. So after several headaches and trying to understand I figured I'd ask here (EDIT: This is something somewhat similar I found [relating to delimiters and splitting number sequences] to what my teacher was asking me and thought it would be adequate to ask it here. So before I get accused of doing my homework on here I wanted to clarify)

Here's what I have typed so far:

import java.io.*;
import java.util.*;
public class addUp
{
   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*"); With some help and research I found 
         out that the \\s* actually causes every character to be split 
         apart. so 33 is 3 3 */

      int sum = sc.nextInt();
      while(sc.hasNextInt( )) 
      {
         String operator = sc.next();
         int value = sc.nextInt();

         if(operator.equals("-"))
         {
            sum = sum - value;
         }

         else if(operator.equals("+"))
         {
            sum = sum + value;
         }
      } 
      System.out.println("Sum is: " + sum); 
   } 
}

And my last attempt got me a weird output:

 ----jGRASP exec: java addUp

Enter something like 8 + 33 + 1345 - 137 : 8 + 33 + 1345 - 137
Sum is: 8

 ----jGRASP: operation complete.

Now I don't know a ton and I'm sure if I came in with something more complicated than the progress of what we've been through would not be appreciated (since I know I've seen some people answer other questions that is way over my understanding). So keep it dumbed down for me if you can XD. Thanks.

Was it helpful?

Solution

The problem with your code at the moment is that your while loop is checking for while(sc.hasNextInt( )), but it's expecting an operator. Change that to while(sc.hasNext() and you should be ok.

Additionally, when facing problems like this, try running your code in a debugger and stepping through it. You'd see pretty quickly that it didn't enter into the while loop and that would help you diagnose the problem. If you don't have access to a debugger, just put in some System.out.println() statements.

UPDATE

So, I ran your code in a debugger (after changing the while loop as I described), and the first thing I noticed was that the first call to sc.nextInt() returns 3, not 33, because of the reason H L explained. Having removed the call to setDelimeter, the code runs fine. It should now look like:

import java.io.*;
import java.util.*;

public class addUp
{
   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*"); <-- don't do this
      int sum = sc.nextInt();
      while(sc.hasNext( )) // <-- not hasNextInt
      {
         String operator = sc.next();
         int value = sc.nextInt();

         if(operator.equals("-"))
         {
            sum = sum - value;
         }

         else if(operator.equals("+"))
         {
            sum = sum + value;
         }
      } 
      System.out.println("Sum is: " + sum); 
   } 
}

And outputs:

Enter something like 8 + 33 + 1345 - 137 : 8 + 33 + 1345 - 137
Sum is: 1249

Again, you should have spotted this if you stepped through your code in a debugger (Eclipse, IntelliJ, NetBeans, jdb, etc).

OTHER TIPS

There are multiple issues with your code:

  1. You call the next() and nextInt() methods multiple times within the while loop which consumes too much of our input.
  2. The sum is initialized to 0 and the very first operand is omitted.
  3. Only the last else block is executed because you compare strings with characters (single quotes instead of double quotes) which always evaluates to false.

Code:

// WRONG: sc.useDelimiter("\\s*");
int sum = sc.nextInt();  // consume the first token, must be an integer
while (sc.hasNext()) {   // as long as there are more tokes, do the following
    String operator = sc.next();  // read next token, must be a + or - sign
    int operand = sc.nextInt();   // read next token, must be an integer again

    // depending on the arithmetic operator we update the sum variable
    if (operator.equals("-")) {
        sum = sum - operand;
    } else if (operator.equals("+")) {
        sum = sum + operand;
    } else {
        // if the operator variable contains something else than a + or - sign
        // we throw an exception. In general this is the preferred way to avoid
        // that the software changes into an undefined state.
        throw new RuntimeException("Unknown operator: " + operator);
    }
}
System.out.println("Sum is: " + sum);

First Problem (Apparently corrected in an edit to the quesiton)

You call sc.next() in every if statement. Call it once, and then use the value when you need it. If you keep calling it, you'll keep eating your input!

String op = sc.next();

if (op.equals('-') {}
else if (op.equals('+') {}
else {}

Second Problem

You never initialize sum to the first number. You skip the first number completely! Start off like this to make sure you consume the first int before you consume the first operator.

int sum = sc.nextInt();

Third Problem

hasNextInt() only returns true if the next token is an int. It returns false if the next token is an operator like "+" or "-". Change your while to loop on hasNext().

The last fix may cause you to consume a "/n" or some other line seperator nonsense on your last iteration of the loop. as it stands, it looks like this will only cause you to print the sum twice. That seems like something you should be able to solve on your own.

Rather than making me edit my answer four MORE times, try to do this on paper, going in circles for the while loop. Consume an int. Consume an operator. Consume an int. Consume an operator. Consume an int. If you break that order, your logic isn't in the right order. Know the logic before you even try to write code.

Go read the Javadoc for Scanner to see what each method you are calling actually does. Learn about Streams in Java so you understand how they work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top