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 4 of 4

Thread: HELP - Summing Numbers, with and without Input

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Exclamation HELP While Loop - Summing Numbers, with and without Input

    Hey I'm trying to teach myself java OO programming using BlueJ and some material from my university, so far it's gone smoothly but I've stumbled on a couple of questions I need help with.


    12.1 a new project:

    Start a new project - call it looping. Add a new class to it - Loops. Start adding a single method to it - any sensible name. In this method, write a do-while loop which prints the numbers from 1 to 5. Then modify your code so that, instead of printing each value in turn, it prints the totals of the numbers from 1 up to that value. So it calculates: 1; 1+2; 1+2+3; 1+2+3+4; 1+2+3+4+5. This means that your solution needs a loop inside a loop.

    12.2: project from qu 12.1, looping

    This question requires keyboard input so you need to make appropriate classes available. One way to do this is to include the InputReader class in your project whose complete code is provided below, though you could use the Scanner class directly, if you prefer. Whichever way you prefer, include code so your Loops class can use a Scanner object.


    import java.util.Scanner;
     
     
    /**
     * InputReader reads typed text input from the standard text terminal. 
     * 
     * @author     Lisa Payne
     * @version    Jan 2007
     */
    public class InputReader
    {
        private Scanner reader;
     
        /**
         * Create a new InputReader that reads text from the text terminal.
         */
        public InputReader()
        {
            reader = new Scanner(System.in);
        }
     
        /**
         * Accesses a String typed in text terminal
         * 
         * @returns String value input
         */
        public String getString()
        {
            String input = reader.nextLine();
            return input;
        }
     
        /**
         * Accesses a int typed on a single line in text terminal
         * 
         * @returns int value input
         */
        public int getInt()
        {
            int input = reader.nextInt();
            reader.nextLine();
            return input;
        }
     
    }

    Start a second method in your Loops class - any sensible name. In this method you need to write code similar to that in question 12.1 (indeed you may want to copy 'n paste that to give you a start). This method should total a series of positive integers which the user enters from the keyboard. The user will type in each value followed by an <Enter> keypress. After the last value the user will type a negative value: this is the terminal sentinel. (Of course this method requires only a single loop - not a loop inside a loop.)
    For question 12.1, I have a solution and it work but I'm not sure it's the most efficient or it does entireley what the question is asking as the 'while' condition doesn't seem to affect much going on. Can somebody check this for me?

        /**
         * Prints totals of numbers between 1 to 5.
         */
        public void calculate()
        {
            int count = 1;
            int total = 0;
            int j;
            do {
                for(j = 1; j <= 5; j++) {
                    total += j;
                    System.out.print(total + " ");
                    count++;
                }
            } while(count < 6);
        }

    For 12.2 I have no idea how to incorporate what is being asked with a loop. Can somebody help?!
    Last edited by SunnyS; October 16th, 2012 at 12:23 PM.


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 262 Times in 231 Posts

    Default Re: HELP - Summing Numbers, with and without Input

    The while loop has me stumped too. Looks useless in my opinion. What I see here is an all too common problem. Writing code to solve the problem.
    Instead write a solution to the problem, and then write code to perform the solution.

    Get a list of steps to take from start to finish. Make sure the steps solve the problem and follow the guidelines. Then start writing code. When you have a question, post the steps, the code you have so far, and any related error messages for the best help. A list of steps can help avoid problems in the code.

  3. #3
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: HELP While Loop - Summing Numbers, with and without Input

    Quote Originally Posted by SunnyS View Post
    ...
    For 12.2 I have no idea how to incorporate what is being asked with a loop. Can somebody help?!
    I agree, completely, with jps. Don't think of a loop as a solution looking for a problem, regardless of how the problem is worded. Think of what you can to to solve the problem.

    For a given problem statement, I like to visualize how a run might look. (I am, maybe one of the last bottom-up guys in this wild and crazy top-down world.) I usually design input and output first, then get to the inner workings of what has to be done to process the input and arrive at the output.

    In purest form my actual design process goes like: Bottom-up, goal-oriented visualization followed by top-down design followed by bottom-up implementation. Real projects tend not to be so precisely defined that they are three absolutely sequential steps.

    Anyhow...

    The I/O is often the most time consuming part of the problem. Robust, informative I/O may take a lot of lines of code, but, remember: That's what the user of your program will see. He/she won't see the cleverness that you incorporated internally in order to come up with the answer.

    For example, I would never write a "real" program that silently waits for a user to do "something" and then spits out a bunch of numbers. Also, keep in mind that when debugging, just throwing a few statements that print some numbers willy-nilly doesn't make it easy for you, the programmer, to know what the heck is happening, so you might as well put the informative stuff in from the get-go. At least that's the way I see it.

    Now, maybe your I/O won't be as verbose as mine, and maybe yours will be worded differently, but here's the way that I could see program 12.2 looking and acting. Program output is blue, user input is black:


    You will asked to enter a sequence of positive integers.
    Enter as many as you like.

    After your last number, enter a negative value.
    Then the sum of your positive integers will be reported.

    So, here goes...

    Enter a positive integer: 12
    Enter another positive integer: 34
    Enter another positive integer: 56
    Enter another positive integer: 78
    Enter another positive integer: -1

    The sum of your positive integers is 180

    Goodbye for now.


    Now: Since the number of user inputs is unknown until the program is actually run, it (obviously, I hope) needs some kind of loop that tests values of "things" the user enters. The program decides whether to use that value and prompt for more input and repeat the loop or to terminate the loop and print the summary.

    OK, now, the actual program design starts, and it is your turn.


    Cheers!

    Z
    Last edited by Zaphod_b; October 16th, 2012 at 04:03 PM.

  4. The Following User Says Thank You to Zaphod_b For This Useful Post:

    SunnyS (October 18th, 2012)

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

    Default Re: HELP While Loop - Summing Numbers, with and without Input

    Wow thanks Z.

    That was really helpful, thanks to you I was able to make a solution and it wasn't so difficult after all.

         /**
         * Prints the sum of entered positive integers.
         */
        public void sumValues()
        {
            int value;
            int sum;
            boolean negative = false;
     
            System.out.println("#######################################");
            System.out.println("You will be asked to enter a sequence");
            System.out.println("of positive integers.");
            System.out.println();
            System.out.println("Enter as many as you like.");
            System.out.println();
            System.out.println("After your last number, enter a");
            System.out.println("negative value.");
            System.out.println();
            System.out.println("Then the sum of your positive integers");
            System.out.println("will be reported.");
            System.out.println();
            System.out.println("So, here goes...");
            System.out.println("#######################################");
            System.out.println();
            System.out.print("- Enter a positive integer: ");
     
            value = myReader.getInt();
            sum = value;
            do {
                if(value > 0) {
                    System.out.print("- Enter another positive integer: ");
                    value = myReader.getInt();
                    sum += value;
                } else {
                    sum -=value;
                    negative = true;
                }
            } while(negative == false);
     
            System.out.println();
            if(sum > 0) {
                System.out.print("The sum of your integers is: ");
                System.out.println(sum);
            } else {
                System.out.println("- Start with a positive integer.");
            }
            System.out.println();
            System.out.println("Goodbye for now.");
        }


    Thanks!

Similar Threads

  1. [SOLVED] reading a stream of numbers from standard input
    By mia_tech in forum What's Wrong With My Code?
    Replies: 7
    Last Post: July 25th, 2012, 12:17 AM
  2. Error with taking float numbers from an input dialog box.
    By deepcrimson76 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 26th, 2012, 12:58 PM
  3. Replies: 13
    Last Post: December 6th, 2011, 01:17 PM
  4. Summing a 4X4 Matrix in JOptionPane
    By Java Neil in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 15th, 2011, 09:15 AM
  5. HELP! Input, numbers, nonsense
    By Corvus in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 26th, 2010, 03:18 PM