0

Hi everyone, java newbie here. I've got a bit of a loose grip on delimiters, which I'm trying to use in this code from project "Add 'em Up" in Blue Pelican Java lesson 17. The code does compile, but I'm not getting the results I want. When I run the code and input the equation given in the first print command, it tells me the 'sum' is 0, which is clearly incorrect. I think it's skipping over the 'while' method completely and using the original 'sum' declared, and I'm not sure why. Any help would be greatly appreciated.

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

public class Tester
{
    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 sc1=new Scanner(s);
        sc1.useDelimiter("");

        String plusMinus=sc1.next();
        int sum=0;
        while(sc1.hasNextInt())
        {
            int m=sc1.nextInt();

        if (plusMinus.equals("+"))
        {
            sum=sum+m;
        }
        else if (plusMinus.equals("-"))
        {
            sum=sum-m;
        }

        }
        System.out.println("Sum is: "+sum);
    }
}
2
Contributors
2
Replies
6
Views
5 Years
Discussion Span
Last Post by stultuske
0

yes, it compiles, but the first time plusMinus has the value "8" and your while loop is never executed, so your sum will always have the original value, which is 0.

0

check this example.

public static void main(String args[])
{
    String s = "8 + 33 + 1345 + 137";
    Scanner sc1=new Scanner(s);
    sc1.useDelimiter(" +");
    String plusMinus=sc1.next();
    int sum=Integer.parseInt(plusMinus);
    while (sc1.hasNext()){
        String sign = sc1.next();
        if ( sign.contains("+")){

            sum += Integer.parseInt(sc1.next());
        }
    }
    System.out.println("Sum is: "+sum);
}

now, let's say you want to add the possibility to subtract, multiply, ..., then this is a good place to start your investigation.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.