Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How do I get the return (sum/3) to return just two decimals back? package studen

ID: 3596627 • Letter: H

Question

How do I get the return (sum/3) to return just two decimals back?

package studentGrades;

public class Student {

private String firstName, lastName;

private Address homeAddress, schoolAddress;

private int firstScore, secondScore, thirdScore;

public Student() {

firstScore = 0;

secondScore = 0;

thirdScore = 0;

}

public Student(String first, String last, Address home, Address school, int test1,

int test2, int test3) {

firstName = first;

lastName = last;

homeAddress = home;

schoolAddress = school;

firstScore = test1;

secondScore = test2;

thirdScore = test3;

}

public void setTestScore(int test, int score) {

if (test == 1) {

firstScore = score;

} else if (test == 2) {

secondScore = score;

} else if (test ==3) {

thirdScore = score;

} else {

System.out.println("You entered and invalid charactor. Your only options for test "

+ "scores are 1, 2, or 3.");

}

}

public int getTestScore(int test) {

int score = -1;

if (test == 1 ) {

score = firstScore;

} else if( test == 2) {

score = secondScore;

} else if ( test == 3) {

score = thirdScore;

} else {

System.out.println("You have entered an invalid character, please choose only from"

+ " 1, 2, or 3.");

} return score;

}

public double average() {

double sum = firstScore + secondScore + thirdScore;

return sum/3; <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

}

public String toString() {

String result;

result = firstName + " " + lastName;

result += " Home Address: " + homeAddress + " ";

result += " School Address: " + schoolAddress + " ";

result += " Test scores are: Test 1: " + getTestScore(1) + ", Test 2: "

+ getTestScore(2) + ", Test 3: " + getTestScore(3) + " The average of the "

+ "test scores is: " + average();

return result;

}

}

Explanation / Answer

public double average() {
double sum = firstScore + secondScore + thirdScore;
return sum/3; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}

There is no way to return a (or even store a ) decimal with two decimal point.

There can be two ways, return them as integer or

(recommended) while displaying display only two decimal point

best way is to use Decimal format

result = firstName + " " + lastName;
result += " Home Address: " + homeAddress + " ";
result += " School Address: " + schoolAddress + " ";
result += " Test scores are: Test 1: " + getTestScore(1) + ", Test 2: "
+ getTestScore(2) + ", Test 3: " + getTestScore(3) + " The average of the "
+ "test scores is: " + df.format(average());

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote