0% found this document useful (0 votes)
5 views2 pages

Java Program for Even and Odd Sums

This Java program uses a while loop to repeatedly: (1) prompt the user to enter a number, (2) check if the input is a valid integer, (3) calculate the sum of even and odd numbers from 1 to the input number, (4) display the results, and (5) ask the user to continue or exit. It initializes variables to track the input, sums, and output strings before using a for loop to iterate from 1 to the input, check for even/odd, and update the running sums and output strings accordingly.

Uploaded by

Claf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Java Program for Even and Odd Sums

This Java program uses a while loop to repeatedly: (1) prompt the user to enter a number, (2) check if the input is a valid integer, (3) calculate the sum of even and odd numbers from 1 to the input number, (4) display the results, and (5) ask the user to continue or exit. It initializes variables to track the input, sums, and output strings before using a for loop to iterate from 1 to the input, check for even/odd, and update the running sums and output strings accordingly.

Uploaded by

Claf
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

Scanner;
public class Assignment {
public static void main(String[] args) {
// TODO Auto-generated method stub
String choice = "Y";
while([Link]("Y") || [Link]("y"))
{
Scanner mychoice;
int num = 0;
int sumEven = 0;
int sumOdd = 0;
String sentEven = "Sum of Even Numbers: ";
String sentOdd = "Sum of Odd Numbers: ";
Scanner one = new Scanner ([Link]);
[Link]("Enter a number:");
String n = [Link]();
boolean isStringInt = false;
try{
[Link](n);
isStringInt = true;
}
catch(NumberFormatException ex){}
if(isStringInt == false){
[Link]("INVALID!");
[Link]("Do you still want to
continue? Type 'Y' to continue while 'N' to exit.");
mychoice = new Scanner([Link]);
choice = [Link]();
}
else if (isStringInt == true)
{
num = [Link](n);
for(int x=1; x <= num; x++){
if(x%2 == 0)
{
sumEven = sumEven + x;
if(x == num || x == num-1){
sentEven = sentEven + x + " = "
+ sumEven;
}
else{
sentEven = sentEven + x + " + ";
}
}
else if(x%2 == 1){
sumOdd += x;
if((x == num) || (x == (num-1))){
sentOdd = sentOdd + x + " = " +
sumOdd;
}

else{
sentOdd = sentOdd + x + " + ";
}
}
}
[Link]("Sum of Even Numbers: " +
sentEven);
[Link]("Sum of Odd Numbers: " +
sentOdd);
[Link]("Do you still want to
continue? Type 'Y' to continue while 'N' to exit.");
mychoice = new Scanner([Link]);
choice = [Link]();
}
}
[Link]("Thank you for using the program!");
}
}

You might also like