My totals will not update. Every time I execute the code the gpa displays 0.0. I added the "gp" to see if the "grade points would update when the user information was entered but it will not. Any help would be great! I looked at the other issues and could not seem to solve mine!
import javax.swing.JOptionPane;
public class GUITestClient {
public static void main(String[] args) {
StudentInfo student = new StudentInfo();
double credits;
String name = JOptionPane.showInputDialog("Please enter your name:");
student.setName(name);
credits = Double.parseDouble(JOptionPane.showInputDialog("Please enter the credits:"));
student.setCredits(credits);
String grade = JOptionPane.showInputDialog("Please enter your grade:");
student.setGrade(grade);
JOptionPane.showMessageDialog(null, student.displayStudentInformation());
}
}
public class StudentInfo {
private String name;
private double totalGradePoints;
private double credits;
private String grade;
private double gpa;
public StudentInfo(){
setGrade(null);
setCredits(0);
setGradePoints(0);
}
public StudentInfo(double credits, double totalGradePoints, String grade){
setGrade(grade);
setCredits(credits);
setGradePoints(totalGradePoints);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public double getCredits() {
return credits;
}
public void setCredits(double credits) {
this.credits = credits;
}
public double getGradePoints() {
return totalGradePoints;
}
public void setGradePoints(double totalGradePoints) {
this.totalGradePoints = totalGradePoints;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public double addClass(double totalGradePoints, String grade){
double gradePoints = 0;
if(grade.equals("A")){
gradePoints = 4.0;
}else if(grade.equals("B")){
gradePoints = 3.0;
} else if(grade.equals("C")){
gradePoints = 2.0;
} else if(grade.equals("D")){
gradePoints = 1.0;}
totalGradePoints = (totalGradePoints +gradePoints);
return getGradePoints();
}
public double getGPA(){
this.setGpa(this.getCredits() / this.getGradePoints());
return this.getGpa();
}
public String displayStudentInformation(){
String output = "";
output = output + "Name: " + this.getName() + "\n";
output = output + "Total Credits: " + this.getCredits() + "\n";
output = output + "Your grade is: " + this.getGrade() + "\n";
output = output + "Your GPA is: " + this.getGpa() + "\n";
output = output + "Press any key to continue!" + "\n";
output = output + "gp" + totalGradePoints + "\n";
return output;
}
}
The problem is with your this.getGradePoints(). it is not a getter of a value and you do not set the value inside the function for the same object instance of your student from StudentInfo student = new StudentInfo();
You have to set all your setter variables on that object 'student' you created.
Try this:
package guitestclient;
import javax.swing.JOptionPane;
public class GUITestClient {
public static void main(String[] args) {
StudentInfo student = new StudentInfo();
double credits;
double gradePoints = 0;
double gradePointsTot = 0;
double gpa = 0;
int classCount = 0;
String name = JOptionPane.showInputDialog("Please enter your name:");
student.setName(name);
do{
credits = Double.parseDouble(JOptionPane.showInputDialog("Please enter the credits:"));
student.setCredits(credits);
String grade = JOptionPane.showInputDialog("Please enter your grade:");
student.setGrade(grade);
//calculates gpa value for grade
gradePoints = StudentInfo.addClass(gradePoints, grade);
gradePointsTot += gradePoints;
classCount++;
} while (classCount < 5);
//after loop
student.setGradePoints(gradePointsTot);
gpa = StudentInfo.getGPA(credits, gpa, classCount);
student.setGpa(gpa);
JOptionPane.showMessageDialog(null, student.displayStudentInformation());
}
}
class StudentInfo {
private String name;
private double totalGradePoints;
private double credits;
private String grade;
private double gpa;
public StudentInfo(){
setGrade(null);
setCredits(0);
setGradePoints(0);
}
public StudentInfo(double credits, double totalGradePoints, String grade){
setGrade(grade);
setCredits(credits);
setGradePoints(totalGradePoints);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public double getCredits() {
return credits;
}
public void setCredits(double credits) {
this.credits = credits;
}
public double getGradePoints() {
return totalGradePoints;
}
public void setGradePoints(double totalGradePoints) {
this.totalGradePoints = totalGradePoints;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public static double addClass(double totalGradePoints, String grade){
double gradePoints = 0;
if(grade.equals("A")){
gradePoints = 4.0;
}else if(grade.equals("B")){
gradePoints = 3.0;
} else if(grade.equals("C")){
gradePoints = 2.0;
} else if(grade.equals("D")){
gradePoints = 1.0;}
totalGradePoints = (totalGradePoints +gradePoints);
return totalGradePoints;
}
public static double getGPA(double totalGradePoints, double credits, double gpa){
gpa = (credits * totalGradePoints)/ credits;
return gpa;
}
public String displayStudentInformation(){
String output = "";
output = output + "Name: " + this.getName() + "\n";
output = output + "Total Credits: " + this.getCredits() + "\n";
output = output + "Your grade is: " + this.getGrade() + "\n";
output = output + "Your GPA is: " + this.getGpa() + "\n";
output = output + "Press any key to continue!" + "\n";
output = output + "gp" + this.getGradePoints() + "\n";
return output;z
}
}
public double addClass(double totalGradePoints, String grade){
double gradePoints = 0;
if(grade.equals("A")){
gradePoints = 4.0;
}else if(grade.equals("B")){
gradePoints = 3.0;
} else if(grade.equals("C")){
gradePoints = 2.0;
} else if(grade.equals("D")){
gradePoints = 1.0;}
totalGradePoints = (totalGradePoints +gradePoints);
}
The problem is in the final statement of addClass. Java is pass-by-value, which means that the totalGradePoints visible here is a local variable, within the addClass method, containing a copy of whatever value you passed when calling addClass. Any updates you make to that value affect only the local copy, not the original variable.
The method signature doesn't need a totalGradePoints parameter. It should be
public double addClass(String grade) {
...
and you need to add the local gradePoints to the class' member variable totalGradePoints.
In your addClass method, you have totalGradePoints as a local variable.
public double addClass(double totalGradePoints, String grade)
You should use the global variable totalGradePoints instead of a local one. So remove that variable so the method looks like
public double addClass(String grade)
But I do not see anywhere that you call the addClass method.
Related
This is the code I have currently.
Below is my object "Student"
`public class Student {
private String name;
private int score;
public Student() {
}
public Student(String name, int score){
this.name = name;
this.score = score;
}
public void setName(String name) {
this.name = name;
}
public void setScore(int score) {
this.score = score;
}
public void readInput() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the student's name: ");
this.name = keyboard.next();
System.out.println("Please enter the student's score: ");
this.score = keyboard.nextInt();
}
public void writeOutput() {
System.out.println("The student's name and score: " + name + ", " + score + "%");
}
public String getName(String name) {
return this.name;
}
public int getScore(int score) {
return score;
}
}`
Then in another class "TestReporter" I am attempting to compute the averageof the array of ourClass[] .
I am also to find the highest score within the ourClass array but don't know how to seperate scores from students , I probably overcomplicated the question but any help would be appreciated.
`import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class TestReporter {
private int highestScore;
private double averageScore;
private Student[] ourClass;
private int numOfStudents;
public TestReporter(){
}
public void getData() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students");
numOfStudents = keyboard.nextInt();
ourClass = new Student[numOfStudents];
for (int i = 0; i < numOfStudents ; i++) {
ourClass[i] = new Student();
ourClass[i].readInput();
}
}
public void computeStats() {
double total = 0;
for (int i = 0; i < numOfStudents; i++) {
total = total + ourClass[i];
}
averageScore = total / ourClass.length;
}
public void displayResults() {
for (Student Student: ourClass) {
Student.writeOutput();
}
}
}`
To get Highest Score declare variable in compute StateStats
public void computeStats() {
double total = 0;
int highestScore = 0;
for (int i = 0; i < numOfStudents; i++) {
int score = ourClass[i].getScore();
total = total;
if(score > highestScore)
highestScore = score;
}
averageScore = total / ourClass.length;
System.output.println("Average Score = "+averageScore;
System.output.println("Highest Score = " highestScore;
}
then add following to displayResults()
computeStats();
Also:
change Setters as mentioned by {QBrute}
I'm writing a program that takes user input for employees. I have some private setters (they have to be private according to the UML) but the method names are underlined grey. I've tried making getters or doing this.variableName to get rid of them, but to be honest I don't have much experience with private setters so I'm unsure of what to do. Also there is no getters for some variables and no default constructor as shown in the UML.
UML:
and here's my code
public class Employee_Kubik {
//variables
private static String name;
private double salary;
private int yearsWith;
private double sales;
public Employee_Kubik(String n, double sala, int y, double sale){
name = n;
salary = sala;
yearsWith = y;
sales = sale;
} //Employee end
public String getName(){
return name;
} //getName end
private void setSalary(double s){
if (s > 0){
salary = s;
} //if end
else{
salary = 0;
} //else end
} //setSalary end
private void setYearsWith(int yw){
if (yw > 0){
yearsWith = yw;
} //if end
else{
yearsWith = 0;
} //else end
} //setYearsWith
private void setSales(double s){
if(s > 0){
sales = s;
} //if end
else{
sales = 0;
} //else end
} //setSales end
public boolean promote(){
if(sales > 9999 && yearsWith > 2){
return true;
} //if end
else{
return false;
} //else end
} //promote end
public double calculateRaise(){
salary = salary * 0.05;
return salary;
} //calculateRaise end
#Override
public String toString(){
return "Employee Name: " +
name +
", has been with the company for " +
yearsWith +
" years and last year sold a total of $" +
sales +
"\nPromotion Status = " +
promote();
} //toString end
} //class end
One place that you can use them in, is your constructor:
public Employee_Kubik(String n, double sala, int y, double sale){
name = n;
setSalary(sala);
setSales(sale);
setYearsWith(y);
}
I've only just begun programming, and I find most of my resources to be incredibly unhelpful. Hopefully you guys can help!
My program runs until it gets to the display methods, and then it just stops. No errors, and no build successful. It just continues with the user input. Any ideas?
Here is all of the program. I created a separate class for the object as well. Let me know if you think the problem could be there. Thanks!
import java.util.Scanner;
public class HernandezMortgageCalculator {
public static void main(String[] args) {
programDescription();
System.out.println();
MortgageLoan mortgageLoan1 = new MortgageLoan();
Scanner userInput = new Scanner(System.in);
System.out.println();
System.out.println("Please enter the home buyer's last name: ");
String lastName = userInput.nextLine();
System.out.println("Please enter the home's zip code: ");
String zipCode = userInput.nextLine();
System.out.println("Please enter the home value: ");
double homeValue = userInput.nextDouble();
System.out.println("Please enter the annual interest rate: ");
double annualInterestRate = userInput.nextDouble();
mortgageLoan1.setLoanIdentifier(mortgageLoan1.getLoanIdentifier());
mortgageLoan1.setHomeValue(userInput.nextDouble());
mortgageLoan1.setLoanAmount();
mortgageLoan1.setAnnualInterestRate(userInput.nextDouble());
System.out.println();
System.out.println();
displayLoanDetails(mortgageLoan1);
displayMortgageResults(mortgageLoan1);
}
public static void programDescription() {
System.out.println("This program implements a Mortgage Calulator");
System.out.println();
System.out.println("Given a home's purchase price and loan's annual" +
"interest rate, it will compute the monthly" +
"mortgage payment, which includes taxes, " +
"insurance principle and interest.");
}
public static void displayLoanDetails(MortgageLoan mortgageLoan1){
System.out.println();
System.out.println("Loan Details");
System.out.printf(" Loan identifier %f "
+ mortgageLoan1.getLoanIdentifier());
System.out.println();
System.out.printf(" Loan amount %.2f "
+ mortgageLoan1.getLoanAmount() );
System.out.println();
System.out.printf(" Loan length %f "
+ mortgageLoan1.getLengthOfLoan() + " years");
System.out.println();
System.out.printf(" Annual Interest Rate %.3f"
+ mortgageLoan1.getAnnualInterestRate() + "%");
System.out.println();
}
public static void displayMortgageResults (MortgageLoan mortgageLoan1) {
double monthlyPropertyTax = mortgageLoan1.calcMonthlyPropertyTax();
double monthlyInsurancePremium =
mortgageLoan1.calcMonthlyInsurancePremium();
double monthlyPrincipleAndLoan =
mortgageLoan1.calcMonthlyPrincipleAndLoan();
double totalMonthlyMortgage = monthlyPropertyTax + monthlyInsurancePremium
+ monthlyPrincipleAndLoan;
System.out.println();
System.out.println("Monthly Mortgage Payment");
System.out.printf(" Monthly Taxes %.2f",
monthlyPropertyTax);
System.out.println();
System.out.printf(" Monthly Insurance %.2f",
monthlyInsurancePremium);
System.out.println();
System.out.printf(" Monthly Principle & Interest %.2f",
monthlyPrincipleAndLoan);
System.out.println();
System.out.println(" --------");
System.out.println();
System.out.printf(" Total Monthly Mortage Payment %.2f",
totalMonthlyMortgage);
}
public class MortgageLoan {
private String loanIdentifier;
private double homeValue;
private double downPayment;
private double loanAmount;
private int lengthOfLoan;
private double annualInterestRate;
public MortgageLoan() {
loanIdentifier = "";
homeValue = 0.0;
downPayment = 10.0;
loanAmount = 0.0;
lengthOfLoan = 30;
annualInterestRate = 0.0;
}
public static char firstFour(String lastName){
char result = lastName.charAt(0);
result += lastName.charAt(1);
result += lastName.charAt(2);
result += lastName.charAt(3);
return result;
}
public static char firstThree(String zipCode){
char result = zipCode.charAt(0);
result += zipCode.charAt(1);
result += zipCode.charAt(2);
return result;
}
public static String lastNameZipCode(String lastName, String zipCode) {
String result = "";
result = lastName.toUpperCase();
result += firstFour(lastName);
result += firstThree(zipCode);
return result;
}
void setLoanIdentifier(String lastNameZipCode) {
loanIdentifier = lastNameZipCode;
}
void setHomeValue(double newHomeValue) {
homeValue = newHomeValue;
}
void setLoanAmount() {
double newLoanAmount = homeValue - homeValue * (downPayment/100);
loanAmount = newLoanAmount;
}
void setAnnualInterestRate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}
public String getLoanIdentifier() {
return loanIdentifier;
}
public double getLoanAmount(){
return loanAmount;
}
public int getLengthOfLoan(){
return lengthOfLoan;
}
public double getAnnualInterestRate(){
return annualInterestRate;
}
public double calcMonthlyPropertyTax() {
final double HOME_ASSED_VALUE_PERCENTAGE = 0.85;
final double ANNUAL_PROPERTY_TAXES_PERCENTAGE = 0.0063;
final double ADMIN_FEE = 35.00;
double homeAssessedValue = homeValue * HOME_ASSED_VALUE_PERCENTAGE;
double annualPropertyTaxes = (homeAssessedValue *
ANNUAL_PROPERTY_TAXES_PERCENTAGE + ADMIN_FEE);
double monthlyPropertyTax = annualPropertyTaxes/12;
return monthlyPropertyTax;
}
public double calcMonthlyInsurancePremium() {
final double ANNUAL_PREMIUM_PERCENTAGE = .0049;
double annualInsurancePremium = .0049 * homeValue;
double monthlyInsurancePremium = Math.round(annualInsurancePremium/12);
return monthlyInsurancePremium;
}
public double calcMonthlyPrincipleAndLoan(){
double monthlyInterestRate = annualInterestRate/100/12;
double Factor = Math.exp((lengthOfLoan*12) * Math.log
(monthlyInterestRate + 1));
double monthlyPrincipleAndLoan = (Factor * monthlyInterestRate *
loanAmount)/(Factor - 1);
return monthlyPrincipleAndLoan;
}
}
I am trying to make a GPA calculator using a while loop with an unknown set of entries. When only one set of information is entered, my program runs fine. If I enter information for more than one class, the totals do not update and I cannot figure out why. Any ideas?
import javax.swing.JOptionPane;
public class GUITestClient {
public static void main(String[] args) {
StudentInfo student = new StudentInfo();
double credits = 0;
double gradePoints = 0;
double gradePointsTot = 0;
double gpa = 0;
String addAnotherClass = null;
String name = JOptionPane.showInputDialog("Please enter your name:");
student.setName(name);
do{
credits = Double.parseDouble(JOptionPane.showInputDialog("Please
enter the credits:"));
student.setCredits(credits);
String grade = JOptionPane.showInputDialog("Please enter your
grade:");
student.setGrade(grade);
addAnotherClass = JOptionPane.showInputDialog("Press "+"Y"+" to
enter More class information");
gradePoints = StudentInfo.addClass(gradePoints, grade);
gradePointsTot += gradePoints;
}while(addAnotherClass.equalsIgnoreCase("y"));
//after loop
student.setGradePoints(gradePointsTot);
StudentInfo.getGPA(credits, gpa, gradePointsTot);
student.setGpa(gpa);
JOptionPane.showMessageDialog(null,
student.displayStudentInformation());
}
}
class StudentInfo {
private String name;
private double totalGradePoints;
private double credits;
private String grade;
private double gpa;
public StudentInfo(){
setGrade(null);
setCredits(0);
setGradePoints(0);
}
public StudentInfo(double credits, double totalGradePoints, String
grade){
setGrade(grade);
setCredits(credits);
setGradePoints(totalGradePoints);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public double getCredits() {
return credits;
}
public void setCredits(double credits) {
this.credits = credits;
}
public double getGradePoints() {
return totalGradePoints;
}
public void setGradePoints(double totalGradePoints) {
this.totalGradePoints = totalGradePoints;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public static double addClass(double totalGradePoints, String grade){
double gradePoints = 0;
double accumGradePoints;
if(grade.equalsIgnoreCase("A")){
gradePoints = 4.0;
}else if(grade.equalsIgnoreCase("B")){
gradePoints = 3.0;
} else if(grade.equalsIgnoreCase("C")){
gradePoints = 2.0;
} else if(grade.equalsIgnoreCase("D")){
gradePoints = 1.0;}
totalGradePoints += gradePoints;
return totalGradePoints;
}
public static double getGPA(double totalGradePoints, double credits,
double gpa){
gpa = (credits * totalGradePoints)/ credits);
return gpa;
}
public String displayStudentInformation(){
String output = "";
output = output + "Name: " + this.getName() + "\n";
output = output + "Total Credits: " + this.getCredits() + "\n";
output = output + "Your grade is: " + this.getGrade() + "\n";
output = output + "Your GPA is:
" + this.getGPA(totalGradePoints, credits, gpa) + "\n";
output = output + "Press any key to continue!" + "\n";
output = output + "gp" + totalGradePoints + "credits" + credits;
return output;
}
}
This question already has answers here:
Why does this Java division print out zero? [duplicate]
(5 answers)
Closed 7 years ago.
I am having problem with my getGPA() method it will only return a 0.00 value. I need for the function to calculate the GPA by dividing totalgradepoints by numberofclasses. I've tried everything and have no idea what the problem is. I am a complete beginner and trying to learn as I go this is for a class assignment so this is what we were instructed by our professor. I appreciate any advice on this thank you everyone.
import java.util.Scanner;
import java.text.DecimalFormat;
public class StudentGPAInfo {
static DecimalFormat f = new DecimalFormat ("0.00");
private double gpa;
private int totalgradepoints;
private int numberofclasses;
private String studentname;
public StudentGPAInfo() {
gpa = 0;
totalgradepoints = 0;
numberofclasses = 0;
studentname = null;
}
public void setName(String studentID){
studentname = studentID;
}
public void addClass(int classes, String gradepoint){
numberofclasses = numberofclasses += classes;
if (gradepoint.equalsIgnoreCase("A")) {
totalgradepoints += 4;
} else if (gradepoint.equalsIgnoreCase("B")) {
totalgradepoints += 3;
} else if (gradepoint.equalsIgnoreCase("C")) {
totalgradepoints += 2;
} else if (gradepoint.equalsIgnoreCase("D")) {
totalgradepoints += 1;
} else if (!gradepoint.equalsIgnoreCase("F")) {
System.err.println("Invalid input: " + gradepoint);
}
}
public String getName(){
return studentname;
}
public double getGPA(){
gpa = totalgradepoints / numberofclasses;
return gpa;
}
public void displayStudent(){
System.out.println("Student Name: " + studentname);
System.out.println("Total Grade Points: " + totalgradepoints);
System.out.println("Number of Class Credits: " + numberofclasses);
System.out.println(studentname + " Your GPA Average is: " + f.format(gpa));
}
}
public class GPAtest {
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String sName;
String grade;
int sClass;
String aClass;
StudentGPAInfo student = new StudentGPAInfo();
System.out.print("Please Enter Student Name: ");
sName = input.nextLine();
student.setName(sName);
do {
System.out.print("Please Enter Class credits: ");
sClass = Integer.parseInt(input.nextLine());
System.out.print("Please Enter Letter Grade: ");
grade = input.nextLine();
System.out.print("Another Class? ");
aClass = input.nextLine();
student.addClass(sClass, grade);
}
while (aClass.equalsIgnoreCase("y"));
student.displayStudent();
}
}
Please read how integer division works. if the numerator is less than the denominator, the result is zero. Make the numerator a double by casting.
Change this:
gpa = totalgradepoints / numberofclasses;
to this:
gpa = (double) totalgradepoints / numberofclasses;