This is java programming. I want to design a program which ask user to input som
ID: 3587490 • Letter: T
Question
This is java programming. I want to design a program which ask user to input some integers. However, user can even type alphabets and special characters. Program will keep asking for inputs while input is not 'q' or 'Q'. When user input is 'q' or 'Q', then system should print the sum of even numbers, sum of odd numbers and product of even and odd numbers. All letters and special characters should be ignored. Modify the following code to meet all the requirements.
import java.util.Scanner;
public class Loop {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers n letters, then q or Q to stop");
int input = sc.nextInt();
int odd, even;
while (input != 'q' || input != 'Q'){
if (isDigit(input)){
if (input% 2 == 0 ){
even += input;
}else{ odd += input;}
}
}
System.out.println("sum of odds is " + odd);
System.out.println("sum of evens is " + even);
System.out.println("their product is " + odd * even);
}
}
Explanation / Answer
Given below is the code for the question with output. Do you need the product of odd numbers separately and even numbers separately ? Looking at the code , it looked like you are multiplying the sum of odds and sum of evens . The fixed program outputs the product of all even numbers separately and all odd numbers separately. Post a comment if you need something different other than the way it is functioning, I will help . If the answered helped, please don't forget to rate it. Thank you.
import java.util.Scanner;
public class Loop {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers, then q or Q to stop");
long oddSum = 0, evenSum = 0;
long oddProduct = 1 , evenProduct = 1;
boolean stop = false;
while (!stop && sc.hasNext()) //check if there is another input token, could be any type
{
if(sc.hasNextInt()) //check if the next input token is of int type
{
int num = sc.nextInt();
if(num % 2 == 0) //the number is even
{
evenSum += num;
evenProduct *= num;
}
else //the number is odd
{
oddSum += num;
oddProduct *= num;
}
}
else //ignore the next non-numeric input, if q / Q then set stop = true so that loop terminates
{
String str = sc.next();
if(str.toLowerCase().equals("q"))
stop = true;
}
}
System.out.println("sum of odds is " + oddSum);
System.out.println("sum of evens is " + evenSum);
System.out.println("product of odds is " + oddProduct);
System.out.println("product of evens is " + evenProduct);
}
}
output
Enter numbers, then q or Q to stop
hello
apple
?
%
---
344%
2
4
3
5
8
q
sum of odds is 8
sum of evens is 14
product of odds is 15
product of evens is 64
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.