1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

How do I write this program ?

  1. Dec 2, 2011 #1
    Write a program to input a whole number n using the Scanner class. If the number is less than 0, your program should print an error message. If the number is 0 or 1, the actual number should be printed. If the number is greater than 1, compute the sum of all integers between 1 and the given number n (1+2+...+n) using a for loop and print this sum.

    it needs to be a for loop

    This was my attempt at writing it, I was going to try it out in steps but bluej keeps giving me red working bar so I think something is wrong:

    Code (Text):
    import java.util.Scanner;

    /*
     * Test Run1
     */
    public class ForLoopandSum {

        public static void main(String[] args) {
           
                 
            int n;
           
            Scanner number = new Scanner(System.in);
           
            n = number.nextInt();
           
            if(n<0){
               
                System.out.println( "You entered " + n);
            }
           
            {
                System.out.println( "Please enter a whole number greater than 0 ");
            }
           
        }
    }
    I made a few modifications but I don't really know how to go forth from here


    Code (Text):
    import java.util.Scanner;

    /*
     * Test Run1
     */
    public class ForLoopandSum {

        public static void main(String[] args) {
           
            Scanner number = new Scanner(System.in);
            System.out.println( "Enter an integer: ");
           
            int n = number.nextInt();
           
            if(n>=0){
                System.out.println( "You entered " +n);
         
            }
           
            else{
                System.out.println( "Please enter a value greater than 0 ");
                                       
            }
           
        }
    }
         
     
    Last edited: Dec 2, 2011
  2. jcsd
  3. Dec 2, 2011 #2

    Mark44

    Staff: Mentor

    I don't know what "bluej keeps giving me red working bar" means. I don't see any obvious syntax errors, but you are missing a lot of the structure that you need in your program.

    When your program starts, it expects the user to type a number. There is no prompt to help the naive user know what is expected. If the naive user guesses that he needs to type a number, there are a couple of things that can happen.
    1) If the user enters, say, -1, the program prints "You entered -1" and then prints "Please enter a whole number greater than 0 " and then exits.
    2) If the user enters, say, 5, the program prints "Please enter a whole number greater than 0 " and then exits.

    Note that this code that you have in braces --
    Code (Text):
            {
                System.out.println( "Please enter a whole number greater than 0 ");
            }
     
    -- suggests that you think something special is happening, but it isn't. That's just a block of code that will execute regardless of the value of n. Adding braces and indenting as you did makes no difference.

    The code you show suggests that you don't have a good handle on the basic algorithm that your program needs to implement.

    Prompt the user to enter a number.
    If the number is negative, print an error message.
    If the number is 0 or the number is 1, print the number.
    If the number is > 1, calculate the sum of 1 + 2 + ... + number, and print this value.

    Calculating the sum is where you would use a for loop.
     
  4. Dec 2, 2011 #3
    Thank you for your comments and input, I'll try to modify my code. I've used "else" to separate the statements so it changed a little bit.

    Bluej is the program I'm using and the red working bar is something like a loading bar and
     
  5. Dec 3, 2011 #4
    Well I wrote my code but then when I write negative numbers it still continues with the and calculates the sum then comes up with 0 as the answer is there a way to make it present me with the option to enter the number again or just give me the error and stop right there ? also what does this line mean : sum += i ? I just tried it out and it happened to work.

    On another note, how come my program doesn't list the numbers between 1 and n like this program ? :

    Code (Text):
    /** ForLoops1.java
        Session 7 demonstration of for loops
        Des, 15th November 2000
    */

    public class ForLoops1
    {
        public static void main(String [] args)
        {
            // Here the loop counter is increasing
            for (int counter = 1; counter <= 10; ++counter )
            {
                System.out.println("Inside loop, counter is " + counter);
            }
        }
    }
    This is my program

    Code (Text):
    import java.util.Scanner;

    public class sumOfN
    {
            public static void main(String[] args)
            {
                    // Initialise Scanner Object
                    Scanner number = new Scanner(System.in);

                    // Requests integer, n
                    System.out.println("Enter an integer: ");
                    int n = number.nextInt();

                    // Reports error if n is less that 0
                    if (n < 0) {
                            System.out.println("The integer must be greater than or equal to 0");
                            // Prints n if n is either 0 or 1
                    } else if (n == 0 || n == 1) {
                            System.out.println(n);
                    }

                    int sum = 0;
                   
                    // loops from 1 to n
                    for (int i = 1; i <= n; i++) {
                        // adds i, the number between 1 and n to the sum
                           sum += i;
                    }
                    System.out.println( "The sum of the numbers between 1 and "+n+" is " +sum);

            }
    }
     
  6. Dec 3, 2011 #5

    Mark44

    Staff: Mentor

    What you write will be more easily understood if you break up long, rambling sentences with punctuation.

    The problem statement doesn't require the program to reprompt the user if a negative number is entered, so this is not anything you need to be concerned about for this exercise. On the other hand, if you're just curious about how that would be done, a while loop could be used, with the loop exiting after a positive number is entered.
    += is one of several compound assignment operators. The statement sum += i; is equivalent to the statement sum = sum + i;

    Some other compound assignment operators are -=, *=, /=, and a few others involving bitwise operators.
    Here is the code that is causing the problem you mentioned.
    Code (Text):

    // Reports error if n is less that 0
    if (n < 0) {
        System.out.println("The integer must be greater than or equal to 0");
        // Prints n if n is either 0 or 1
    } // ***You really should put else on its own line, to make it easier to find.***
    else if (n == 0 || n == 1) {
        System.out.println(n);
    }

    int sum = 0;
                   
    // loops from 1 to n
    for (int i = 1; i <= n; i++) {
        // adds i, the number between 1 and n to the sum
        sum += i;
    }
    System.out.println( "The sum of the numbers between 1 and "+n+" is " +sum);
     
    If the user enters a negative number, the program displays a warning, and then tries to calculate the sum. It should not do this.
    If the user enters 0 or 1, the program displays the number, and then tries to calculate the sum. It should not do this either.

    What you need to do is put the block of code starting with int sum = 0 and the final println statement into a final else clause. With that change, the sum will be calculated only if the input number is greater than 1.
     
  7. Dec 3, 2011 #6
    How do I write that ? I'm completely lost :s
     
  8. Dec 3, 2011 #7

    Mark44

    Staff: Mentor

    Like this.
    Code (Text):

    int sum = 0; // Moved from below.
    .
    .
    .
    if (n < 0)
    {
        System.out.println("The integer must be greater than or equal to 0");
    }
    // Prints n if n is either 0 or 1
    else if (n == 0 || n == 1)
    {
        System.out.println(n);
    }

    else
    {
                   
       // loops from 1 to n
       for (int i = 1; i <= n; i++)
       {
          // adds i, the number between 1 and n to the sum
          sum += i;
       }
       System.out.println( "The sum of the numbers between 1 and "+n+" is " +sum);
    }
     
     
  9. Dec 3, 2011 #8
    Thank you for your assistance, I didn't know I could use the if else statement like that.

    I appreciate the help :)
     
  10. Dec 3, 2011 #9

    Mark44

    Staff: Mentor

    Yes, you can create a logical structure that chooses one alternative among as many as you want.
    Code (Text):

    if (<condition_1>)
    {
       ...
    }

    else if (<condition_2>)
    {
       ...
    }

    else if (<condition_3>)
    {
       ...
    }
    .
    .
    .
    else if (<condition_n>)
    {
       ...
    }

    else
    {
       ...
    }
     
     
  11. Dec 4, 2011 #10

    Many thanks, I'll try to write some programs and see how it works out for me :)
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: How do I write this program ?
  1. How do I find voltage? (Replies: 3)

Loading...