what was wrong with the logic? import java.util.Scanner; import static java.lang
ID: 3891504 • Letter: W
Question
what was wrong with the logic?
import java.util.Scanner; import static java.lang.System.out; public class Mean { public static void main(String[] args){ Scanner sc =new Scanner(System.in); System.out.println("Welcome to the Mean Calculator"); String s;int a;int b=0;int c=0; do { do{System.out.println("Please enter your number:"); if(sc.hasNextInt()) {a=sc.nextInt();break;} else{System.out.println("Numbers Only!");}}while(true); do{ System.out.println("Do you wish to enter another number?(y/n):"); s=sc.nextLine(); if(!(s.equals("y")||s.equals("n"))){ System.out.println("Please enter y or n!"); }else{break;} }while (true); b++;c=c+a; }while(s.equals("y")); System.out.printf("Sum: %d Num: %d",c,a); double m=c/a; System.out.printf("Mean: %.1f",m); System.out.println("Thank you for using Mean Calculator"); } } Welcome to the Mean Calculator Please enter your number: 3 Do you wish to enter another number?(y/n): Please enter y or n! Do you wish to enter another number?(y/n): y Please enter your number: 3 Do you wish to enter another number?(y/n): Please enter y or n! Do you wish to enter another number?(y/n): n Sum: 6 Num: 3Mean: 2.00Thank you for using Mean Calculator
Explanation / Answer
Please find below the corrected program
import java.util.Scanner;
import static java.lang.System.out;
class Mean {
public static void main(String[] args){
System.out.println("Welcome to the Mean Calculator");
Scanner sc =new Scanner(System.in);
String s;
int a;int b=0;int c=0;
do {
do{
System.out.println("Please enter your number:");
if(sc.hasNextInt())
{a=sc.nextInt();
b++;
break;
}
else{System.out.println("Numbers Only!");}
}while(true);
do{ System.out.println("Do you wish to enter another number?(y/n):");
s=sc.nextLine();
if(!(s.equals("y")||s.equals("n"))){
System.out.println("Please enter y or n!");
}
else{ break;}
}while (true);
//b++;
c=c+a;
}while(s.equals("y"));
System.out.printf("Sum: %d Num: %d ",c,b);
double m=c/b;
System.out.printf("Mean: %.1f ",m);
System.out.println("Thank you for using Mean Calculator");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.