R1 chagg. Yahoo! ? Official Apples l ? (2) lawa For Beg khan academy lee wki 0-1
ID: 3909601 • Letter: R
Question
R1 chagg. Yahoo! ? Official Apples l ? (2) lawa For Beg khan academy lee wki 0-1+r × laa A-Beginne //c/Users/Tesfay/Downloads/C$200-1-HW4.pdf Part 4a: Create a Java class named YourName4a so mine would be carden4a.java Your program will do the following: 1. Prompt the user to enter an odd integer x 2. Continue to prompt the user for x until the user enters an odd integer 3. The program will then print all the odd integers between 1 and x that are multiples of three Below are two sample runs: ?“jGRASP exec : java Cardena Enter an odd integer: 4 Enter an odd integer: 6 Enter an odd integer: 2 Enter an odd integer: 9 3 is a multiple of 3 3 is a multiple of 9 jGRASP exec: java Carden4a Enter an odd integer: 2 Enter an odd integer: 13 3 is a multiple of 3 3 is asultiple of 9 jGRASP: operation complete. GRASP: operation conplete. Part 4b: Create a Java class named YourName4b so mine would be Carden4b.java Your class needs a main method, but for now just leave it erExplanation / Answer
4a.
import java.util.*;
class YourName4a
{
public static void main (String[] args)
{
int x;
Scanner input = new Scanner(System.in);
do
{
System.out.println("Enter an odd integer : ");
x = input.nextInt();
}
while(x%2 ==0); // loop continues if x is even
for(int i=1;i<=x;i++)
{
if(i%3 == 0) // check if i is multiple of 3
System.out.println(i+" is a multiple of 3");
}
}
}
Output:
Enter an odd integer :4
Enter an odd integer :6
Enter an odd integer :2
Enter an odd integer :9
3 is a multiple of 3
6 is a multiple of 3
9 is a multiple of 3
4b.
import java.util.*;
class YourName4b
{
public static void main (String[] args)
{
int evenNumber = getInput();
System.out.println("Sum of all even numbers between 2 and "+evenNumber +" is : "+sumAllEvens(evenNumber));
}
public static int getInput()
{
int x;
Scanner input = new Scanner(System.in);
do
{
System.out.println("Enter an even integer : ");
x = input.nextInt();
}
while(x%2 !=0); // loop continues if x is not even
return x;
}
public static int sumAllEvens(int x)
{
int sum = 0;
for(int i=2;i<=x;i++)
{
if(i%2 == 0) // if i is even
sum = sum + i; // add i to sum
}
return sum;
}
}
Output:
Enter an even integer :7
Enter an even integer :3
Enter an even integer :12
Sum of all even numbers between 2 and 12 is : 42
Do ask if any doubt. Please upvote.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.