Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Easy help but can't figure it out.

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Easy help but can't figure it out.

    ok I managed to get this working correctly. The code is to take in a string and add the numbers what I am trying to change is to also allow subtraction including checking the first number for a + or - sign. I have tried many things but I guess I am not seeing hot to set the If statement for that seems to be what would work. NOt sure how to check for - or + using the scanner. Any help would be great.

     
     
    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 sc = new Scanner(s);
     
           sc.useDelimiter("\\s*\\+\\s*"); 
           int sum = 0;
           while(sc.hasNextInt( ))
           {
             sum = sum + sc.nextInt( );
           }
     
     
           System.out.println("Sum is: " + sum);
       }
    }
    Last edited by weezer562; October 19th, 2010 at 07:03 PM. Reason: fixing comma in code


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Question Re: Easy help but can't figure it out.

    Quote Originally Posted by weezer562 View Post
    ok I managed to get this working correctly. The code is to take in a string and add the numbers what I am trying to change is to also allow subtraction including checking the first number for a + or - sign. I have tried many things but I guess I am not seeing hot to set the If statement for that seems to be what would work. NOt sure how to check for - or + using the scanner. Any help would be great.

     
     
    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 + 1,345 +137 : ");
           String s = kb.nextLine( ); 
           Scanner sc = new Scanner(s);
     
           sc.useDelimiter("\\s*\\+\\s*"); 
           int sum = 0;
           while(sc.hasNextInt( ))
           {
             sum = sum + sc.nextInt( );
           }
     
     
           System.out.println("Sum is: " + sum);
       }
    }
    The Scanner class can't add for you.

    To take the values you have in a String and make them into numbers, you use the wrapper classes.

    Integer.parseInt(String str);
    Double.parseDouble(String str);
    Long.parseLong(String str);

    But you can only do that with one String at a time. Inputting 8+5 will make a String called "8+5", which is a String.

    Scanner(String source)
    Constructs a new Scanner that produces values scanned from the specified string.

    Again, I don't see how nextInt() will work for Strings. You can't take in "7+5" as a String and expect it to print out 12.

    At least, not to my knowledge.

  3. The Following User Says Thank You to javapenguin For This Useful Post:

    weezer562 (October 19th, 2010)

  4. #3
    Junior Member
    Join Date
    Oct 2010
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Easy help but can't figure it out.

    It is actually stopping at the + symbol and then adding the nextInt this does work , my problem is adding subtraction to the mix. I have tried adding an If statementwithin the while loop , but with no luck not sure what the conditional statement would be.

  5. #4
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Easy help but can't figure it out.

    System.out.print("Enter something like 8 + 33 + 1,345 +137 : ");

    I'm not sure if the int thing will recognize commas.

  6. #5
    Junior Member
    Join Date
    Oct 2010
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Easy help but can't figure it out.

    Fixed that took out the example but in that code if a person enters lets say 20 + 35 + 45 it should work. It has for me.

  7. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Easy help but can't figure it out.

    Quote Originally Posted by weezer562 View Post
    It is actually stopping at the + symbol and then adding the nextInt this does work , my problem is adding subtraction to the mix. I have tried adding an If statementwithin the while loop , but with no luck not sure what the conditional statement would be.
    Ok, well you have used + has a delimiter but you want both. I would do this a different way.

    NOTE: But for my way to work, there needs to be 1 requirement. There must be a space before and after the minus or plus sign. With some trickery, that can probably be fixed, but I'm not wanting to go so in depth.
    I would read in the line instead of each int. That would return to you a String. You can then use the String.split(" ") method. That will return a String[] where each index is either a number or a plus or minus. So, you would only need a conditional statement to see if a value is a plus or minus symbol. If it isn't either, then you know it is a number. Even better than that, you know that every even index will be a number and every odd index will be a mathematical symbol. Here is my code (please don't use for class, but instead as an alternative way of doing it):
    import java.util.Scanner;
     
    public class TestRead 
    {
     
        public static void main(String[] args) 
        {
        	//Create Scanner Object
        	Scanner kb = new Scanner(System.in);
        	//Prompt User
    	    System.out.print("Enter something like 8 + 33 + 1345 + 137: ");
    	    //Get User Input
    	    String s = kb.nextLine();
     
    	    //Create split of User Input
    	    String[] line = s.split(" ");
     
    	    //Results Variable
    	    int result = 0;
    	    //Boolean to tell us to add or subtract
    	    boolean plus = true;
     
    	    //Loop through User Input split
    	    for(int i=0;i<line.length;i++)
    	    {
    	    	//Check if this index is odd for increased efficency
    	    	if(i%2==1)
    	    	{
    	    		//Check if this index holds a plus sign
    		    	if(line[i].equals("+"))
    		    		plus = true;
    		    	//Check if this index holds a minus sign
    		    	else if(line[i].equals("-"))
    		    		plus = false;	
    	    	}
    	  		//If this is an even index
    	    	else
    	    	{
    	    		//If we want to add numbers
    	    		if(plus)
    	    			result += Integer.parseInt(line[i]);
    	    		//If we want to subtract numbers
    	    		else
    	    			result -= Integer.parseInt(line[i]);
    	    	}
    	    }
    	    //Print out result
    	   	System.out.println(result);
        }
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. #7
    Junior Member
    Join Date
    Oct 2010
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Easy help but can't figure it out.

    Completely agree with you, but my assignment was to get both addition and subtraction working using scanner methods. I believe its being used to get us accustomed to this. I really appreciate all the input.

  9. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Easy help but can't figure it out.

    Quote Originally Posted by weezer562 View Post
    Completely agree with you, but my assignment was to get both addition and subtraction working using scanner methods. I believe its being used to get us accustomed to this. I really appreciate all the input.
    Ok, well we can modify this to do something similar. Once again, if there are spaces between the numbers and symbols, we can use the next() method while the scanner hasNext(). Then, if you keep a count of how many times you call that next() method, you can tell if it is a symbol or number (even are numbers and odd are symbols, starting from 0). You can then do basically the same thing I did above.

    That way we are using the scanner methods but still doing the same thing technically.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. I'm new at this and can't figure it out
    By jaheh06 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: September 22nd, 2010, 08:44 AM
  2. My Custom Layout (VERY EASY TO USE)
    By aussiemcgr in forum AWT / Java Swing
    Replies: 10
    Last Post: August 5th, 2010, 01:37 PM
  3. A Few Quick, Easy Questions
    By TheAsianMenace in forum Object Oriented Programming
    Replies: 1
    Last Post: February 24th, 2010, 02:47 PM
  4. String + Compare // Might be too easy for ya
    By Jangan in forum Java Theory & Questions
    Replies: 1
    Last Post: October 18th, 2009, 05:40 PM
  5. [SOLVED] Java program to prompt and display the user input number as odd or even
    By napenthia in forum Java Theory & Questions
    Replies: 11
    Last Post: April 22nd, 2009, 01:19 AM