This do while business is getting easier! Total coding time was like 45 minutes. Most wasted time was spent trying to figure out why the compiler would not recognize the variable stop in the very last line of code.
Problem solved by declaring variables outside of all loops, statements, etc. I tried to declare it as it was inputted, but I guess the do while loop needs to know it is coming before the do part!
import java.util.Scanner;
public class SumOfEvens
{
public static void main(String[] args)
{
//declare variables
int sum = 0, stop, num;
//allow user to rerun if desired
do
{
//create scanner and receive input integer
System.out.print("Enter an integer between 20 and 60: ");
Scanner input = new Scanner(System.in);
num = input.nextInt();
//resets sum to zero in subsequent iterations
sum = 0;
//loop starts at two, determines if incremented number is even
//and stops when entered integer is reached
for (int i = 2; i <= num; i++)
{
//number is even if modulo is zero
if (i % 2 == 0)
//sum accumulates the added digits
sum = sum + i;
}
//Print results
System.out.println("Entered value: " + num);
System.out.println("Sum of even numbers between 2 and " + num + " is: " + sum);
//prompts user to go again
System.out.print("Continue (0 to end)? ");
stop = input.nextInt();
}
//ends program if user enters 0
while (stop != 0);
}
}
Useful site: http://stackoverflow.com/questions/25706216/what-does-a-cannot-find-symbol-compilation-error-mean
No comments:
Post a Comment