Page 1 of 2 12 LastLast
Results 1 to 20 of 30
  1. #1
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default add all the numbers in a string

    i have a string that contains something like this:
    7
    6
    4
    5
    6
    2
    1
    2
    1
    2
    2
    5
    1
    2
    14
    5
    2
    3
    3
    9
    what can i use to add all the numbers in this string? not just the amount of numbers, but add all the values of each number together?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    Java Code:
    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;
            
            
            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);
            while (inFile.hasNext())
            {
             token = inFile.next( );
    
                      
            }      
            inFile.close();
            
            
            
           
                       
                      
    
    
                  
               
    
            }
         }
    the string is an input from a txt file. i need something that will give me the sum of all the numbers so i can divide it by numTrials and get an average to output.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Your code has little to do with the problem at hand and in fact appears to be solving a different problem. Did you download this code from some online source?

  5. #5
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    no i didnt, it is an assignment and i dont know how to do a particular part. i am supposed to output a txt file that has the number of times it takes to win a 1 in 5 chance of winning a drink top game. then i import it back and use it to calculate an average number that you would have to buy in order to win. im sure it is right up until this point where i dont know how to get a sum of all the output so i can get an average. i cant use parsing because im just testing with 20 trials, but when i submit it has to use 1000 trials, and thats too many variable to make.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You need to parse the Strings in the file one way or another. Even if you use the Scanner and call nextInt, the Strings are being parsed behind the scenes in the Scanner. I suggest that you do just this, change your while loop to read while (in.hasNextInt()) and read in the ints with in.nextInt into an int variable, and then add this int into a summation variable. Increment a counter variable each time an int is read in. Then you should be able to figure out how to solve this problem.

  7. #7
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    im sorry, but i cant really follow what your saying. im very new, can i get like a kind of skeleton of an example of what you mean?

  8. #8
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    alright i dont know if this is right, but i have done this:
    Java Code:
    while (inFile.hasNext())
            {
             token = inFile.next( );
             
             
             int total = Integer.parseInt(token);
             System.out.print(total);
    
                      
            }      
            inFile.close();
    but the only problem is that the numbers are outputting like this:
    143211381111121623112
    i dont know how to add them all together. is there one command that can add all the numbers in a string together and set it as an int?

  9. #9
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    i have parsed the number, but now i need to add each individual number together.

  10. #10
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Don't think on the compiler. Write out your algorithm before you start typing out your code.
    You will be getting numbers inside the loop and adding the numbers to a running total. The running total must start at zero before the loop starts and needs to be available after the loop ends.

  11. #11
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    Quote Originally Posted by r035198x View Post
    Don't think on the compiler. Write out your algorithm before you start typing out your code.
    You will be getting numbers inside the loop and adding the numbers to a running total. The running total must start at zero before the loop starts and needs to be available after the loop ends.
    thats my problem. i dont know how to break the string down and add all the numbers to a running total. no one understands what i mean.:confused:

  12. #12
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    I do. You don't seem to be understanding my response though because it tells you how to solve the problem.

  13. #13
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    well, in theory you answered my question, but in reality i already know the answer, i just dont know how to apply it to code. this is my entire problem, this might make it easier for you to feel my pain.
    Java Code:
    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;
           
           
            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);
            while (inFile.hasNext())
            {
             token = inFile.next( );
                      
             
    
                     
            }     
            inFile.close();
           
           
           
          
                      
                     
    
                 
              
            }
         }
    these are my exact instructions:

    Instructions: Write a program that uses the Monte Carlo sampling method to estimate the
    average number of bottles of Boost someone would have to drink to win a prize. There is a one
    in five chance that a bottle cap will have a prize.
    1. Create a new project called 5.06 Monte Carlo Method in the
    Mod05 Assignments folder.
    2. Create a class called BottleCapPrize in the newly created
    project folder.
    3. Determine how many times a die must be rolled in order to
    win a prize. (This represents one trial.) Print this value to a
    text file.
    4. Conduct at least 1,000 trials.
    5. Read the data back in from all of the trials.
    6. Calculate the average number of times a die must be rolled in order to win a prize.
    7. Print the result to the screen.
    Suggestion: Write this program in stages. First, work on the part that conducts trials and
    print the results to the screen; however, during testing only use about 20 trials. Second,
    print the results of each trial (the number of rolls to get a prize) to a file. Check the file to
    verify it matches the screen output. Third, read the trial data back in and calculate the
    average. Fourth, print the results.
    Expected Output: When your program runs, your output should simply print a message
    indicating the average number of bottles of Boost you would need to drink to win a prize
    i am at the end. i have been on this one assignment for almost a week and it is driving me crazy. i have no idea how to get it to work, and i am in a distance learning class so i dont have a teacher to ask. maybe what im asking now makes a little more sense.

  14. #14
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    int total = 0;
    while(there are still some numbers to be added) {
    read a number.
    add the value of that number to the total

    }
    total now has the sum.

  15. #15
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    how do you read a number from a string of several numbers? i mean i get what your saying, i know what to do in pseudo code, but i dont know the actual statements to use to get the result i need so i can calculate the average and then print it.

  16. #16
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Look at your first post. The numbers are on different lines aren't they?
    So read one line at a time => read one number at a time.
    How to calculate the average? As the total loop is running, add a count variable that counts how many times the loop ran. The rest should be obvious from there.

  17. #17
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    "So read one line at a time => read one number at a time. " <-------------this is what i am trying to figure out how to do.

  18. #18
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    If you use FileReader/BufferedReader combination then you'll find the readLine method very useful. If you use the Scanner then that you will only need to be calling nextInt to get the next number. Read the API specs for those classes and methods.

  19. #19
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by gibson.nathan View Post
    "So read one line at a time => read one number at a time. " <-------------this is what i am trying to figure out how to do.
    This was explained already in reply #6 above. What about that don't you understand?

  20. #20
    gibson.nathan is offline Member
    Join Date
    Sep 2009
    Posts
    11
    Rep Power
    0

    Default

    Java Code:
     
            int sum = 0;
            while (in.hasNextInt())
            {
             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(); 
          
                      
                     
    
                 
              
            }
         }
    alright, i have this. i tried to do everything that was stated. when i compile and run my virtual machine in blue j just goes and produces no output. usually that happens when a loop isnt satisfied. does my code look kind of similar to what you guys were talking about? does anyone know if a loop isnt satisfied, or anything that could cause my virtual machine to stay tied up?

Page 1 of 2 12 LastLast

Similar Threads

  1. parsing numbers in a string
    By rsoler in forum Advanced Java
    Replies: 4
    Last Post: 03-31-2009, 06:05 AM
  2. Replies: 5
    Last Post: 01-11-2009, 10:12 AM
  3. printing two smallest numbers from a series of numbers
    By trofyscarz in forum New To Java
    Replies: 2
    Last Post: 10-14-2008, 11:46 PM
  4. Replies: 0
    Last Post: 11-20-2007, 04:59 PM
  5. validating a string for numbers and letters?
    By lockmac in forum New To Java
    Replies: 1
    Last Post: 08-09-2007, 09:17 AM

Posting Permissions

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