Flash Website Builder- Trendy Site Builder is a Flash Site Building tool that helps users build stunning websites. Check Out Custom Custom Logo Design by LogoBee. Website Design and Free Logo Templates available.
 CodingForums.com How to sum integers in an array ?

Before you post, read our: Rules & Posting Guidelines

Enjoy an ad free experience by logging in. Not a member yet? Register.
 01-23-2011, 06:59 PM PM User | #1 minimalistic New to the CF scene   Join Date: Jan 2011 Posts: 4 Thanks: 2 Thanked 0 Times in 0 Posts 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 !
 01-23-2011, 07:23 PM PM User | #2 ShaneC 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 InputArray = new Vector(); // 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! __________________ 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 Last edited by ShaneC; 01-23-2011 at 07:36 PM..
 Users who have thanked ShaneC for this post: minimalistic (01-23-2011)
 01-23-2011, 08:16 PM PM User | #3 minimalistic New to the CF scene   Join Date: Jan 2011 Posts: 4 Thanks: 2 Thanked 0 Times in 0 Posts 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.
 01-23-2011, 08:35 PM PM User | #4 ShaneC 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. __________________ 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 Last edited by ShaneC; 01-23-2011 at 08:56 PM.. Reason: Forgot the divide operation!
 Users who have thanked ShaneC for this post: minimalistic (01-23-2011)
 01-23-2011, 09:30 PM PM User | #5 minimalistic 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 09:48 PM..
 01-23-2011, 10:04 PM PM User | #6 ShaneC 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
01-23-2011, 10:16 PM   PM User | #7
minimalistic
New to the CF scene

Join Date: Jan 2011
Posts: 4
Thanks: 2
Thanked 0 Times in 0 Posts
Quote:
 Originally Posted by ShaneC 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.

 01-23-2011, 10:42 PM PM User | #8 ShaneC 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

 Bookmarks

 Tags arrays, input, java

 Thread Tools Rate This Thread Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is Off Forum Rules
 Forum Jump User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home :: Client side development     JavaScript programming         DOM and JSON scripting         Ajax and Design         JavaScript frameworks         Post a JavaScript     HTML & CSS     XML     Flash & ActionScript         Adobe Flex     Graphics and Multimedia discussions     General web building         Site reviews         Building for mobile devices :: Server side development     Apache configuration     Perl/ CGI     PHP         Post a PHP snippet     MySQL         Other Databases     Ruby & Ruby On Rails     ASP     ASP.NET     Java and JSP     Other server side languages/ issues         ColdFusion         Python :: Computing & Sciences     Computer Programming     Computer/PC discussions     Geek News and Humour Web Projects and Services Marketplace     Web Projects         Small projects (quick fixes and changes)         Medium projects (new script, new features, etc)         Large Projects (new web application, complex features etc)         Unknown sized projects (request quote)         Vacant job positions         Looking for work/ for hire         Project collaboration/ partnership         Paid work offers and requests (Now CLOSED)     Career, job, and business ideas or advice     Domains, Sites, and Designs for sale         Domains for sale         Websites for sale         Design templates and graphics for sale :: Other forums     Member Offers     Forum feedback and announcements

All times are GMT +1. The time now is 09:14 PM.