So basically I'm stuck at the do-while statement. Should I use a do while? or a for loop?

This program is supposed to test my ability to use loops.

/*Create an application that reads an integer value and prints the sum of all even integers between 2
 * and the input value, inclusive. Print an error message if the input value is less than 2.
 */
import java.util.Random;

public class Project3 
	{
	public static void main (String[]args)
		{
		int critical,test,count = 2;
		
		Random rand = new Random ();
		
		critical = rand.nextInt(21);
		test = critical % 2;
		
		System.out.println("The random number is: " + critical);
		
		if (test == 1)
			System.out.println("Not an even number. Thank you, come again!");
		else
			{
			do
				{
				System.out.println(count + count);
				count += 2;
				}
			while (count != critical);
			}
		}
	}

GOT IT!

Critiquing is welcome though. Anything to help me be a better coder. Thank you in advanced.

Btw...is this an example of a nested-if?

/*Create an application that reads an integer value and prints the sum of all even integers between 2
 * and the input value, inclusive. Print an error message if the input value is less than 2.
 */
import java.util.Random;

public class Project3 
	{
	public static void main (String[]args)
		{
		int critical,test,count = 2;
		int result = 0;
		
		Random rand = new Random ();
		
		critical = rand.nextInt(19)+2;
		test = critical % 2;
		
		System.out.println("The random number is: " + critical);
		if (critical == 2)
			System.out.println(critical + critical);
		else
		{
		if (test == 1)
			System.out.println("Not an even number. Thank you, come again!");
		else
			{
			do
				{
				result = count + result;
				count += 2;
				System.out.println(result);
				}
			while (count != critical);
			System.out.println(critical + result);
			}
		}
		}
	}

Edited 4 Years Ago by ibthevivin: Additional question

looks pretty good to me, and yes, that is a nested-if structure, although here you could use the else if instead of else{ if () .. }

most of the times, you'll find nested if's in the form of

if ( expression1 ){
  if ( expression2 ){

  }
}

but what you do is equal to

if ( !expression1 ){
  if ( expression2 ){

  }
}
This article has been dead for over six months. Start a new discussion instead.