i have an integer like this:1
4
3
2
1
1
3
8
1
1
1
1
1
2
1
6
2
3
1
12
what can i do to add each individual number together like this: 4+3+2+1+1+1+3+8 etc?

Recommended Answers

All 15 Replies

I'm confused about the question. What do you mean you have an integer like this? Need more info

sir according to me
u have to push all numbers in a stack and thn using plus opretor pop out these all thn u will get sum of all numbers

When you are reading these integers in from your file, you can either insert them into an array, or just add them together as you read the line. When you read a line in from file, if you read it as text do the following to convert it to an integer:

String lineData;
int numberOfRolls;
int total = 0;

//while not end of file
//the line below is pseudo-code--meaning a combination
//of Java and plain English, it is up to you to write it properly in Java
while (!eof){ 
     //To Do: read line from file and put it in variable "lineData"

     //Optional: see if data contains only numeric values
     //(hint: use "isInteger")

     //convert String to int
     numberOfRolls = Integer.parseInt(lineData);

     //add numbers together as they are read in
     total = total + numberOfRolls;
}

The only thing, is that "Integer.parseInt(lineData)" will throw an error if lineData contains data that can't be converted to an integer. To prevent this you can check the data before trying it. There are two versions of a method called "isInteger" in the following post that will check the data:
http://www.daniweb.com/forums/post999241.html#post999241 . But you wrote the data to the file and you know that it only contains integers, so checking to see if the data is an integer may be unnecessary.

sir according to me
u have to push all numbers in a stack and thn using plus opretor pop out these all thn u will get sum of all numbers

No stack is required to calculate the sum. Set up a sum variable and initialize it to 0. Read in a value. Add it to the sum. Read in the next value. Add it to the sum. Keep doing this till you've read in all the numbers.

int sum = 0;

while (/* you haven't read all of the numbers from the file*/)
{
   // read in a number from the file.
   // add the number you just read to the sum.
}

// sum now contains the sum of all the numbers in the file.

No stack is required to calculate the sum. Set up a sum variable and initialize it to 0. Read in a value. Add it to the sum. Read in the next value. Add it to the sum. Keep doing this till you've read in all the numbers.

int sum = 0;

while (/* you haven't read all of the numbers from the file*/)
{
   // read in a number from the file.
   // add the number you just read to the sum.
}

// sum now contains the sum of all the numbers in the file.

thank you for your help. you skeleton makes alot of sense, but im still not sure about what all statements i am supposed to use.

That would depend on the details you haven't supplied - such as where this data is coming from.

int sum = 0;
        while (inFile.hasNext())
        {
         token = inFile.next( );
         int num = Integer.parseInt(token);
         int nums = in.nextInt();
         
         sum = nums + nums;
         
         int average = sum/numTrials;
         
         System.out.println(average);

             
        }     
        
       
       
        inFile.close();

would this be right?

int sum = 0;
        while (inFile.hasNext())
        {
         token = inFile.next( );
         int num = Integer.parseInt(token);
         int nums = in.nextInt();
         
         sum = nums + nums;
         
         int average = sum/numTrials;
         
         System.out.println(average);

             
        }     
        
       
       
        inFile.close();

would this be right?

You tell us. Does it run? Do you get the right results? Short answer is no. It won't work. Think about what is inside the loop and what is not. Suppose you have ten numbers in the file. The code inside the loop should execute inside ten times. Take a list of ten numbers on paper and compute the average on paper. What do you do ten times on paper? What do you do once? It'll be the same in the program. Do everything very precisely when you compute on paper and keep track of what you do. Do not skip any steps. Then write your program around that. Everything happens either before, inside, or after the loop.

besides what happens in or out of the loop, are my statements right? that was my main concern, i can figure out what goes where in the loop.

It is not clear that how you input the numbers, is it from keyboard internal variables. Please specify the problem more clearly.

It is not clear that how you input the numbers, is it from keyboard internal variables. Please specify the problem more clearly.

the numbers are generated in the program and then written to a file. the file is then imported back in and that is where i am trying to get the numbers from.

You can directly assign these values to an array looping as many time as the count of numbers u have. And then after storing the values in array you can add array elements.
initialize
sum= 0
for(i = 1;i<=n;i++)
{
sum = sum + a
}

Hope this helps

besides what happens in or out of the loop, are my statements right? that was my main concern, i can figure out what goes where in the loop.

That's not a good approach to programming. A line is correct if it's the right line AND it's in the right spot. Since there is more than one way to do everything, a line could be "right" if it's in one place and "wrong" if it's in another, or vice versa. Put the lines where you think the correct place is, then run the program and see if you're right. If you can figure out where everything is supposed to go, why are things in the incorrect place now?

int sum = 0;
        while (inFile.hasNext())
        {
         token = inFile.next( );
         int num = Integer.parseInt(token);
         int nums = in.nextInt();
         
         sum = nums + nums;
         
         int average = sum/numTrials;
         
         System.out.println(average);

             
        }     
        
       
       
        inFile.close();

would this be right?

You should post more code. We can probably figure out what type inFile should be and how we might do it and how it's set up, but perhaps we'd be guessing wrong and giving advice based on faulty assumptions. Is inFile a Scanner? Is in a Scanner? Why do you have two different variables here.

Line 9 is incorrect no matter where you put it. Lines 11 and 13 might be correct depending on where you put them. We don't know where numTrials comes from and how it gets its value, so no comment there except that if you don't know before reading the file what this variable's value is, it will be the wrong value.

That's not a good approach to programming. A line is correct if it's the right line AND it's in the right spot. Since there is more than one way to do everything, a line could be "right" if it's in one place and "wrong" if it's in another, or vice versa. Put the lines where you think the correct place is, then run the program and see if you're right. If you can figure out where everything is supposed to go, why are things in the incorrect place now?

You should post more code. We can probably figure out what type inFile should be and how we might do it and how it's set up, but perhaps we'd be guessing wrong and giving advice based on faulty assumptions. Is inFile a Scanner? Is in a Scanner? Why do you have two different variables here.

Line 9 is incorrect no matter where you put it. Lines 11 and 13 might be correct depending on where you put them. We don't know where numTrials comes from and how it gets its value, so no comment there except that if you don't know before reading the file what this variable's value is, it will be the wrong value.

import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class BottleCapPrize
{
    public static void main(String [] args)throws IOException 
    {
        Scanner in; 
        in = new Scanner(System.in);
       
       
        int numTrials = 20;
        int average = 0;
       
        PrintWriter outFile = new PrintWriter (new File("bottleCap.txt"));
 
      
  
      for (int i = 0; i < numTrials; i++)
  
      {
  
      int counter = 0;
  
      int randomNumber = 0;
 
      
 
      do
 
      {
 
      randomNumber = ((int)(0+ Math.random()* 5));
 
      counter++;
 
      }
 
      while (randomNumber != 1);
 
      
 
      outFile.println(counter);
 
      }
 
      
 
        outFile.close ( );
       
        String token = "";
        File fileName = new File("bottleCap.txt");
        Scanner inFile = new Scanner(fileName);
        
        int sum = 0;
        while (in.hasNextInt())
        {
         token = inFile.next( );
         int num = Integer.parseInt(token);
         int nums = in.nextInt();
         
         sum = nums + nums;
         
         average = sum/numTrials;
         
         

             
        }    
	
	System.out.println(average); 
        
       
       
        inFile.close(); 
      
                  
                 

             
          
        }
     }

this is my code. i think that i have everything right to make it work, but when i run my virtual machine gets tied up. if someone knows what the problem is, throw me some help.

Lines 58 and 62 - in is your Scanner for input from the keyboard. If lines 58 through 71 aren't reading from the keyboard at all, you shouldn't use in there.

Line 64 - as mentioned previously, this is incorrect. See the earlier posts in this thread regarding how to calculate a running sum.

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.