How to Create a Logical Structure with Multiple Alternatives in Java

  • Thread starter Thread starter Darkstar3000
  • Start date Start date
  • Tags Tags
    Program
AI Thread Summary
The discussion focuses on creating a Java program that takes a whole number input and processes it based on its value. If the input is negative, an error message is displayed; if it's 0 or 1, the number is printed. For numbers greater than 1, the program calculates the sum of all integers from 1 to that number using a for loop. Participants address issues with the code structure, particularly ensuring that the sum calculation only occurs when appropriate, and clarify the use of the compound assignment operator. The conversation concludes with encouragement to experiment further with Java programming.
Darkstar3000
Messages
28
Reaction score
0
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:
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:
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:
Physics news on Phys.org
Darkstar3000 said:
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:
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 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:
        {
            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.
 
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
 
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:
/**	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:
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);

        }
}
 
Darkstar3000 said:
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 ?
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.
Darkstar3000 said:
also what does this line mean : sum += i ? I just tried it out and it happened to work.
+= 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.
Darkstar3000 said:
On another note, how come my program doesn't list the numbers between 1 and n like this program ? :

Code:
/**	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:
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);

        }
}

Here is the code that is causing the problem you mentioned.
Code:
// 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.
 
Mark44 said:
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.

How do I write that ? I'm completely lost :s
 
Like this.
Code:
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);
}
 
Mark44 said:
Like this.
Code:
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);
}

Thank you for your assistance, I didn't know I could use the if else statement like that.

I appreciate the help :)
 
Yes, you can create a logical structure that chooses one alternative among as many as you want.
Code:
if (<condition_1>)
{
   ...
}

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

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

else
{
   ...
}
 
  • #10
Mark44 said:
Yes, you can create a logical structure that chooses one alternative among as many as you want.
Code:
if (<condition_1>)
{
   ...
}

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

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

else
{
   ...
}


Many thanks, I'll try to write some programs and see how it works out for me :)
 

Similar threads

Replies
7
Views
2K
Replies
7
Views
3K
Replies
12
Views
2K
Replies
1
Views
2K
Replies
3
Views
6K
Replies
2
Views
2K
Replies
3
Views
1K
Back
Top