Design and implement 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. Prompt accordingly.
Right now for the following problem i have this:
import java.util.Scanner;
public class Multiples
{
//-----------------------------------------------------------------
// Prints multiples of a user-specified number up to a user-
// specified limit.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int PER_LINE = 1;
int value, limit, mult, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a value: ");
value = scan.nextInt();
limit = scan.nextInt();
mult = scan.nextInt();
System.out.println ();
System.out.println ("The sum of the even numbers between 2 and " + mult + " (inclusive) are:");
for (mult = value; mult <= limit; mult+= value)
{
System.out.print (mult + "\t");
count++;
if (count % PER_LINE == 0)
System.out.println();
}
}
}
as of right now all i can do is enter the value, hit return andnothing happens.
how can i after entering the value, it adds up all the even numbers between 2 and the value entered?
01-09-2005, 03:30 PM
JGRobinson
Hi,
I'm not really sure exactly what all of the variables where for, but based on the initial question here is a solution.
Code:
package test;
import java.util.Scanner;
public class Main
{
//-----------------------------------------------------------------
// Prints multiples of a user-specified number up to a user-
// specified limit.
//-----------------------------------------------------------------
public static void main(String[] args)
{
int limit = 0;
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Limit: ");
limit = scan.nextInt();
System.out.println();
System.out.println("The sum of the even numbers between 2 and " + limit + " (inclusive) are:");
for (int count = 1; count <= limit; count++)
{
// Only add if even
if((count & 1)!= 1)
{
sum+=count;
System.out.println(count);
}
}
System.out.println("The sum is " + sum);
}
}
run it using java test/Main from an command window