How to Create a Logical Structure with Multiple Alternatives in Java

  • Thread starter Darkstar3000
  • Start date
  • Tags
    Program
In summary: That is not what you want. You want a conditional statement that checks to see if the number is less than 0, and if it is, prints an error message. You also want a conditional statement that checks to see if the number is 0 or 1, and if it is, prints the number. If the number is not 0 or 1, you want to compute the sum of all integers between 1 and the given number n (1+2+...+n) using a for loop and print this sum. I won't write the code for you.
  • #1
Darkstar3000
29
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
  • #2
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.
 
  • #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
 
  • #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:
/**	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);

        }
}
 
  • #5
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.
 
  • #6
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
 
  • #7
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);
}
 
  • #8
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 :)
 
  • #9
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 :)
 

Related to How to Create a Logical Structure with Multiple Alternatives in Java

What language should I use to write my program?

The language you use will depend on the requirements of your project. Some popular programming languages include Python, Java, C++, and JavaScript. Consider factors such as your level of expertise, the purpose of the program, and its intended platform when choosing a language.

How do I plan and design my program?

Before starting to write your program, it's important to have a clear plan and design in place. This includes outlining the purpose of the program, identifying the necessary inputs and outputs, and breaking down the problem into smaller, manageable tasks. Flowcharts, pseudocode, and UML diagrams are useful tools for planning and designing your program.

What are the key components of a well-written program?

A well-written program should have a clear and concise purpose, be easy to read and understand, and have efficient and organized code. It should also handle errors and exceptions gracefully, use appropriate naming conventions, and include comments to explain complex sections of code.

How do I test and debug my program?

Testing and debugging are crucial steps in the programming process. To test your program, you can use various methods such as unit testing, integration testing, and user testing. Debugging involves identifying and fixing errors in your code. Tools like debuggers and print statements can help with this process.

How do I continue learning and improving my programming skills?

Programming is a constantly evolving field, and it's important to continue learning and improving your skills. Some ways to do this include practicing regularly, working on personal projects, and learning from more experienced programmers. Online resources, books, and coding communities are also great sources of knowledge and support.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
18
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
12
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
3
Views
807
  • Programming and Computer Science
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
2
Replies
37
Views
4K
Back
Top