This is what I am trying to do:
the user needs to enter 4 numbers (already done)
then I want to calculate the average of those 4 digits but The first digit needs to counts 1x, the second digit 2x, the third digit 3x and the fourth digit 4x. (already done)
(this is the part where i am stuck)
Also calculate the highest number. If the highest grade is more than 3 points above the average, the screen will show:
cheater!
-1
If the highest grade is less than 3 points above the average, the actual average will appear on the screen, rounded to 1 decimal place.
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i;
double sum;
double number;
double result = 0;
for (i = 1; i < 5; i ) {
number = sc.nextDouble();
sum = number * i;
result = sum;
if (number%result > 3) {
System.out.println("cheater!\n" "-1.0");
} else{
System.out.printf("%3.1f", result / 10);
}
}
}
}
As you can see above here, this is what I got for now. Don't know exactly what I am doing wrong here?
These are my input/results:
5.5
6.1
7.3
5.8
0.6cheater!
-1.0
cheater!
-1.0
cheater!
-1.0
Expected results:
Sample Input 1:
5.5
6.1
7.3
5.8
Sample Output 1:
6.3
Sample Input 2:
3.0
5.4
9.8
2.5
Sample Output 2:
cheater!
-1.0
CodePudding user response:
- to calculate average you need the sum(sum variable) divide by amount of numbers(4 in your case)
- you need to use array to find the highest number
- the if logic is incorrect
I suggest:
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double sum;
double[] number = new double[4];
double result = 0;
double highestNum = 0;
for (int i = 0; i <= 3; i ) {
number[i] = sc.nextDouble();
sum = number[i] * i;
if(highestNum<number[i]){
highestNum = number[i];
}
}
double aveNum = sum/4;
if ((highestNum-aveNum)> 3) {
System.out.println("cheater!\n" "-1.0");
} else{
System.out.printf("%3.1f", result / 10);
}
}
}
CodePudding user response:
double sum;
double number;
double result = 0;
double max = 0;
//Compute the sum
for (int i = 1; i < 5; i )
{
number = sc.nextDouble();
sum = number * i;
result = sum;
if (max < number)
max = number;
}
//Average
double average = Math.Round((double)result / 10, 1);
//Compare to data
if (max > average 3)
System.out.println("cheater!\n" "-1.0");
else
System.out.printf("%3.1f", average);