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);
    }
}

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.