Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New to the CF scene
    Join Date
    Jan 2011
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Exclamation How to sum integers in an array ?

    I've been trying to write a program that will prompt you on:

    • How many variables you want to work with
    • What those variables are
      - Input variable # 1:
      - Input variable # 2: ...
    • Prompt for operation:
      - I'm trying to add everything up right now.

    And so far I've only done this:

    Code:
    import java.io.*;
    import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) throws IOException {
    {
    BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
            Scanner scanner = new Scanner (System.in);
            String a;
     System.out.println ("number of:");
    a = dataIn.readLine();
    int v = Integer.parseInt(a);
    
       ArrayList bb = new ArrayList();
       Scanner in = new Scanner(System.in);
             for (int b = 0; b < v; b++) {
                 int k = b+1;
    System.out.println("input variable #:" +k);
    bb.add(in.next());
         }
     System.out.print(bb);
       float sum =0 ; int i;
       Object xx[] = bb.toArray();
    
            for (i = 0; i < xx.length; i++) {
                sum = sum + xx[i];
            }
    
            System.out.println(sum);
    
      }
    
    }}
    its not working , please help !

  • #2
    Codeasaurus Rex
    Join Date
    Jun 2008
    Location
    Redmond, WA
    Posts
    659
    Thanks
    31
    Thanked 100 Times in 94 Posts
    I think you may be overcomplicating this a bit. You can achieve this very naturally using Vectors, and Iterator element, as well as the wonderful Parse Integer property of Integer.

    Take a look this example I've coded for you. I've included some comments:

    Code:
    import java.util.*;
    import java.lang.*;
    
    class JavaTest {
    
    	public static void main( String[] args ){
    
            // This creates a new Vector with the properties of an integer
    		Vector<Integer> InputArray = new Vector<Integer>();
    		
    		// Add elements to the vector
            // Don't forget to use a try{}catch{} to catch exceptions
            try {
                InputArray.add( 12 );
                InputArray.add( 7 );
                InputArray.add( 42 );
                InputArray.add( -18 );
            }catch( Exception e ){
                System.out.println( "An invalid input has been entered!" );
                System.exit( 1 );
            }
    
    	// Create an Iterator object for the vector
    	Iterator itr = InputArray.iterator();
    	
    	System.out.println( "Please wait while we add the Vector elements..." );
    		
    	int sum = 0;
    	while( itr.hasNext() )
                 // Integer.parseInt takes the string returned to use from the
                 // iterator element and makes it a value we can use.
    	     sum += Integer.parseInt( itr.next().toString() );
    			
    	System.out.println( "The sum of the input values is " + sum );
    	
            }
    
    }
    Though I mentioned it in the code, you must be very careful to validate the input you're getting form the user using try{}catch{} statements. If I entered "Fish" into the input stream, for example, instead of a valid integer then your program would crash when it tried to add Fish to the Vector array.

    With that, when entering, be sure to follow this kind of method:

    Code:
    try{
         Scanner scanIn = new Scanner( System.in );
         VectorName.add( Integer.parseInt( scanIn.next() ) );
    }catch( Exception e ){
         System.out.println( "You've entered an invalid entry! Integers only!" );
         System.exit( 1 );
    }
    Hope this helps!
    Last edited by ShaneC; 01-23-2011 at 06:36 PM.
    Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
    My posts, comments, code, and suggestions reflect only my personal views.
    Web Portfolio and Code Snippets: http://shanechism.com

  • Users who have thanked ShaneC for this post:

    minimalistic (01-23-2011)

  • #3
    New to the CF scene
    Join Date
    Jan 2011
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Arrow

    It worked! Thank you

    But now that it's working I don't know how to change the operation for the array elements.
    Like say I want it to be multiply/subtract/divide instead of add.

    I was looking around and I only found examples of how to sum them.

  • #4
    Codeasaurus Rex
    Join Date
    Jun 2008
    Location
    Redmond, WA
    Posts
    659
    Thanks
    31
    Thanked 100 Times in 94 Posts
    Pretty much the same way, you just add a conditional statement. So lets say you're storing the operation code in the variable opCode. Where 0 is add, 1 is subtract, 2 is multiply, and 3 is divide.

    You would then just replace this block:
    Code:
    int sum = 0;
    while( itr.hasNext() )
    		 // Integer.parseInt takes the string returned to use from the
    		 // iterator element and makes it a value we can use.
    	 sum += Integer.parseInt( itr.next().toString() );
    		
    System.out.println( "The sum of the input values is " + sum );
    With this:
    Code:
    int result = 0;
    
    if( opCode == 0 ){
    	// Adding
    	while( itr.hasNext() )
    		result += Integer.parseInt( itr.next().toString() );
    }else if( opCode == 1 ){
    	// Subtracting
    	while( itr.hasNext() )
    		result = result - Integer.parseInt( itr.next().toString() );
    }else if( opCode == 2 ){
    	// Multiplying
    	// Correct for multiplication by 0
    	result = 1;
    	while( itr.hasNext() )
    		result = result * Integer.parseInt( itr.next().toString() );
    }else if( opCode == 3 ){
    	// Dividing
    	// Correct for dividing from 0
    	result = 1;
    	while( itr.hasNext() )
    		result = result / Integer.parseInt( itr.next().toString() );
    }
    
    System.out.println( "The operational result of the input values is " + result );
    Keep in mind this is a VERY sloppy method, I just wanted to be as clear as possible. If it were me I probably would've done either a switch statement or a function that took in the opCode and performed the operation.

    Edit: Just so you know, I totally missed the part of your original post where your assignment asks the person how many variables they want to work with. That actually makes it much simpler. You can use int[] InputArray = new int[numVars]; where numVars is the entry you got from the user. Then, you just loop through the array adding entries until the array is full.
    Last edited by ShaneC; 01-23-2011 at 07:56 PM. Reason: Forgot the divide operation!
    Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
    My posts, comments, code, and suggestions reflect only my personal views.
    Web Portfolio and Code Snippets: http://shanechism.com

  • Users who have thanked ShaneC for this post:

    minimalistic (01-23-2011)

  • #5
    New to the CF scene
    Join Date
    Jan 2011
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Code:
    result = result / Integer.parseInt( itr.next().toString() );
    I still can't get this part to work though as the answer always comes up as 0.
    ============
    And may I ask why you consider the if else method to be very sloppy?
    I mean I always use it and I just want to know the cons of using that instead of the switch statement.

    and again THANKS for the replies
    Last edited by minimalistic; 01-23-2011 at 08:48 PM.

  • #6
    Codeasaurus Rex
    Join Date
    Jun 2008
    Location
    Redmond, WA
    Posts
    659
    Thanks
    31
    Thanked 100 Times in 94 Posts
    Yes, the divide isn't working because an integer is automatically rounded. So unless your first and only variable is 1 then it will come up as 0.

    When you say divide the variables what do you mean? The first variable divided by the second and so on? You'd have to adapt the code for that.

    As for the switch vs. the if-else. There's conditions to use both, for simplicity sake I'd say just stick to the if-else for now.
    Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
    My posts, comments, code, and suggestions reflect only my personal views.
    Web Portfolio and Code Snippets: http://shanechism.com

  • #7
    New to the CF scene
    Join Date
    Jan 2011
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by ShaneC View Post
    When you say divide the variables what do you mean? The first variable divided by the second and so on? You'd have to adapt the code for that.
    Yes I meant having the first variable divide by the second then the third ...
    and now I'm lost.

  • #8
    Codeasaurus Rex
    Join Date
    Jun 2008
    Location
    Redmond, WA
    Posts
    659
    Thanks
    31
    Thanked 100 Times in 94 Posts
    You're making out like a crook. Typically I don't do this much coding for an assignment posting, but I feel obligated to since I missed components of your post and sent you down the wrong track.

    I highly recommend you do not just copy this verbatim. A) You won't learn anything. B) If your teacher Googles your assignment you'll get pegged for cheating.

    Read the code below, pay attention to the comments, and ask any questions you have on it. This should show you pretty conclusively how you can adapt your current program to have the right effect.

    Code:
    import java.util.*;
    
    class JavaTest {
    
    	public static void main( String[] args ){
    
            // Get this value from a user using a scanner
            int numVariables = 2;
    
            if( numVariables < 2 ){
                System.out.println( "You need two or more variables in order to perform an operation!" );
                System.exit( 1 );
            }
    
            int[] inputArray = new int[numVariables];
    
            Scanner stdin = new Scanner( System.in );
            for( int i = 0; i < inputArray.length; i++ ){
                // Read in values to the array. Like this:
                try{
                    System.out.print( "\nEnter integer #" + ( i + 1 ) + ": " );
                    inputArray[i] = Integer.parseInt( stdin.next() );
                }catch( Exception e ){
                    // Invalid input was entered, set the loop one iteration in the past
                    System.out.println( "Invalid input variable.\n" );
                    i--;
                }
            }
    
            // All values are now in the array
            System.out.println( "Which operation would you like to do?" );
            System.out.println( "1: Add" );
            System.out.println( "2: Subtract" );
            System.out.println( "3: Multiply" );
            System.out.println( "4: Divide" );
    
            // YOU NEED TO VALIDATE THIS. IS IT 1- 4? IS IT A VALID INTEGER?
            System.out.print( "\nEnter your choice: " );
            int opCode = Integer.parseInt( stdin.next() );
    
            int result = inputArray[0];
            String method = "";
    
            if( opCode == 1 ){
                // Addition
                method = "addition";
                for( int i = 1; i < inputArray.length; i++ )
                    result += inputArray[i];
            }else if( opCode == 2 ){
                // Subtraction
                method = "subtraction";
                for( int i = 1; i < inputArray.length; i++ )
                    result -= inputArray[i];
            }else if( opCode == 3 ){
                method = "multiplication";
                for( int i = 1; i < inputArray.length; i++ )
                    result = result * inputArray[i];
            }else if( opCode == 4 ){
                method = "division";
                for( int i = 1; i < inputArray.length; i++ )
                    result = result / inputArray[i];
            }
    
            System.out.println( "\nThe result of the " + method + " is " + result );
            System.exit( 1 );
    	
    	}
    
    }
    Side note: Because everything is in integers, dividing something but another thing will result in the integer without the remainder.
    Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
    My posts, comments, code, and suggestions reflect only my personal views.
    Web Portfolio and Code Snippets: http://shanechism.com


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •