Private Setter saying setter method is "not used" - java

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);
}

Related

How to print out functions from a loop of an array of objects in java

How can I be able to print out the objects that I gave the program in case 2
What I'm trying to implement is case 2 giving me all the info about the stuff I put into case 1
At first I tried to just use the setters and getters but for some reason I was having a NullPointerException when I used the do-while method.
So I decided to use the constructor but at the same time it gave me an error when trying to implement case 2. so any help would be appreciated.
import java.util.Scanner;
public class GameProject {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
do{
GameSale[] game;
System.out.println("Hello! welcome to the menu!");
System.out.println("Please Choose your option!");
System.out.println(" 1-Enter a new game's Info \n 2-Check a game's Information \n 3- Check a game's sales \n 0-Exit");
choice = input.nextInt();
switch (choice){
case 0:
break;
case 1:
System.out.println("");
System.out.print("How many games do you want to add? : ");
int size = input.nextInt();
game = new GameSale[size];
for (int i = 0; i < size; i++) {
System.out.print("Enter Game "+(i+1) + "'s Name!: \n");
String tempname = input.next();
System.out.print("Enter the ID of the Game : \n");
int tempid = input.nextInt();
System.out.print("Enter the Game Type : \n");
String tempgametype=input.next();
System.out.print("Enter the development Company's Name : \n");
String tempgamecomp = input.next();
System.out.print("Enter the Release Sale : \n");
double temprelsale = input.nextDouble();
System.out.print("Enter the total Sales : \n");
double temptotsale = input.nextDouble();
game[i]=new GameSale(temprelsale,temptotsale,tempid,tempname,tempgamecomp,tempgametype);
}break;
case 2:
for(int i = 0; i < game.length; i++){
System.out.println(game[i].toString());
}
}while(choice!=0);
}
}
i got a class that has the setters and getters for some of the regular info
public class GameInfo {
protected int ID;
protected String GameName;
protected String DevelopmentCompany;
protected String GameType;
public GameInfo(int ID, String GameName, String DevelopmentCompany, String GameType) {
this.ID = ID;
this.GameName = GameName;
this.DevelopmentCompany = DevelopmentCompany;
this.GameType = GameType;
}
public void SetID(int id) {
this.ID = id;
}
public int GetID() {
System.out.println("The ID is " + ID);
return ID;
}
public void SetName(String Name) {
this.GameName = Name;
}
public String GetName() {
System.out.println("The Name of the Game Is " + GameName);
return GameName;
}
public void SetCompanyName(String CompanyName) {
this.DevelopmentCompany = CompanyName;
}
public String GetCompanyName() {
System.out.println("The Name Of the Development company Is " + DevelopmentCompany);
return DevelopmentCompany;
}
public void SetGameType(String GameType){
this.GameType=GameType;
}
public String GetGameType(){
System.out.println("The Game Type is : "+GameType);
return GameType;
}
}
and a super class with the sales and a constructor for the sales
public class GameSale extends GameInfo {
protected double ReleaseSales;
protected double TotalSales;
public GameSale(double ReleaseSales, double TotalSales, int ID, String GameName, String DevelopmentCompany, String GameType) {
super(ID, GameName, DevelopmentCompany, GameType);
this.ReleaseSales = ReleaseSales;
this.TotalSales = TotalSales;
}
public void SetReleaseSales(double RelSale){
this.ReleaseSales=RelSale;
}
public void SetTotalSales(double totSales){
this.TotalSales=totSales;
}
public double GetReleaseSales(){
System.out.println("The Release Sales Are "+ReleaseSales );
return ReleaseSales;
}
public double GetTotalSales(){
System.out.println("The Total Sales Are "+TotalSales);
return TotalSales;
}
}
Answered by Alex (thanks a lot dude)
here's a temporary fix just for debugging so far by initializing the array dimensions outside the do-while loop
main
import java.util.Scanner;
public class GameProject {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
int choice;
GameSale[] games = new GameSale[1];
do {
System.out.println("Hello! welcome to the menu!");
System.out.println("Please Choose your option!");
System.out.println(" 1-Enter a new game's Info \n 2-Check a game's Information \n 3- Check a game's sales \n 0-Exit");
choice = input.nextInt();
switch (choice) {
case 0:
break;
case 1:
for (int i = 0; i < games.length; i++) {
System.out.print("Enter Game " + (i + 1) + "'s Name!: \n");
String tempname = input.next();
System.out.print("Enter the ID of the Game : \n");
int tempid = input.nextInt();
System.out.print("Enter the Game Type : \n");
String tempgametype = input.next();
System.out.print("Enter the development Company's Name : \n");
String tempgamecomp = input.next();
System.out.print("Enter the Release Sale : \n");
double temprelsale = input.nextDouble();
System.out.print("Enter the total Sales : \n");
double temptotsale = input.nextDouble();
games[i] = new GameSale(temprelsale, temptotsale, tempid, tempname, tempgamecomp, tempgametype);
}
break;
case 2:
for (int i = 0; i < games.length; i++) {
System.out.println(games[i].toString());
}
}
} while ( choice != 0 );
}
}
game info
public class GameInfo {
protected int ID;
protected String GameName;
protected String DevelopmentCompany;
protected String GameType;
public GameInfo(int ID, String GameName, String DevelopmentCompany, String GameType) {
this.ID = ID;
this.GameName = GameName;
this.DevelopmentCompany = DevelopmentCompany;
this.GameType = GameType;
}
public void SetID(int id) {
this.ID = id;
}
public int GetID() {
System.out.println("The ID is " + ID);
return ID;
}
public void SetName(String Name) {
this.GameName = Name;
}
public String GetName() {
System.out.println("The Name of the Game Is " + GameName);
return GameName;
}
public void SetCompanyName(String CompanyName) {
this.DevelopmentCompany = CompanyName;
}
public String GetCompanyName() {
System.out.println("The Name Of the Development company Is " + DevelopmentCompany);
return DevelopmentCompany;
}
public void SetGameType(String GameType){
this.GameType=GameType;
}
public String GetGameType(){
System.out.println("The Game Type is : "+GameType);
return GameType;
}
}
game sale
public class GameSale extends GameInfo {
protected double ReleaseSales;
protected double TotalSales;
public GameSale(double ReleaseSales, double TotalSales, int ID, String GameName, String DevelopmentCompany, String GameType) {
super(ID, GameName, DevelopmentCompany, GameType);
this.ReleaseSales = ReleaseSales;
this.TotalSales = TotalSales;
}
public void SetReleaseSales(double RelSale){
this.ReleaseSales=RelSale;
}
public void SetTotalSales(double totSales){
this.TotalSales=totSales;
}
public double GetReleaseSales(){
System.out.println("The Release Sales Are "+ReleaseSales );
return ReleaseSales;
}
public double GetTotalSales(){
System.out.println("The Total Sales Are "+TotalSales);
return TotalSales;
}
public String toString(){
return this.ID + " " + this.GameName + " " + this.DevelopmentCompany + " " + this.GameType;
}}
Solution
toString()
In your class you should implement a toString() method.
This basically returns all the property values of your object as a String
public String toString(){
return this.ID + " " + this.GameName + " " + this.DevelopmentCompany + " " + this.GameType;
}
Then call it on your object in case2
game[i].toString()
Display
To list all games you have to iterate over your gamesArray and print out the informations with your toString() method;
for(int i = 0; i < games.length(); i++){
System.out.println(game[i].toString());
}
Scope
Create the games array outside of you case1 scope.
GameSale[] game = new GameSale[SomeFixedSize];
If you wanted to print a game's info at a given index in case 2:
if (game == null) { // Break if no game exists
System.out.println("There is no games to show!");
break;
}
System.out.print("Enter game index to show information: ");
int index = input.nextInt();
// Break if index is not in bounds
if (index < 0 || index > game.length) {
System.out.println("Incorrect index");
break;
}
System.out.println("Info of game: " + game[index].toString());
This code should ask for index as input and prints the info of the game and it will print 'There is no games to show!' if there was no any game added yet
Note you must add the toString() method in your GameSale class:
#Override
public String toString() {
return "ID: " + this.ID + " Name: " + this.GameName + " Development Company: " +
this.DevelopmentCompany + " Game Type: " + this.GameType + " Release Sales: " + ReleaseSales + " Total Sales: " + TotalSales;
}
also move the decleration of the game variable out of the scope of the do-while loop (above it) it will look like
GameSale[] game = null;
do { ...
Also if you want case 2 to show all games info you can replace the index part with a loop that iterates the whole 'game' array and prints every element's toString.

Conflicting Packages PersonManager App Java

So my problem is that when im trying to get a result for my Person manager app and for some reason after a bunch of trial and error i get a result like this
run:
Welcome to the Person Manager
Create customer or employee? (c/e): c
First name: Steve Last name: Trevor Customer number: M10963
You entered a new pkg8.pkg2.person.manager.Customer: Name: Steve
Trevor CustomerNumber: M10963
Continue? (y/n):
now everything is alright up until I get "You entered a new pkg8.pkg2.person.manager.Customer:"
The pkg8.pkg2.person.manager. shouldn't be there.
here is my code
PersonManager.java
package pkg8.pkg2.person.manager;
/**
*
* #author Zachary
*/
public class PersonManager {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Welcome to the Person Manager");
System.out.println("");
String choice = "y";
while (choice.equalsIgnoreCase("y")){
String type = Console.getString("Create customer or employee? (c/e): " , "c", "e");
System.out.println("");
String firstName = Console.getString("First name: ");
String lastName = Console.getString("Last name: ");
Person person;
if(type.equalsIgnoreCase("c")){
String customerNumber = Console.getString("Customer number: ");
person = new Customer(firstName, lastName, customerNumber);
}else{
String ssn = Console.getString("SSN: ");
person = new Employee(firstName, lastName, ssn);
}
Class c = person.getClass();
System.out.println("");
System.out.println("You entered a new " + c.getName() + ":");
System.out.println(person.toString());
System.out.println("");
System.out.println("");
choice = Console.getString("Continue? (y/n): ", "y", "n");
System.out.println();
}
}
}
Person.java
package pkg8.pkg2.person.manager;
/**
*
* #author Zachary
*/
public class Person {
private String firstName;
private String lastName;
public Person(String first, String last){
firstName = first;
lastName = last;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
#Override
public String toString(){
return "Name: " + firstName + " " + lastName;
}
}
Customer.java
package pkg8.pkg2.person.manager;
/**
*
* #author Zachary
*/
public class Customer extends Person {
private String customerNumber;
public Customer(String first, String last, String number) {
super(first, last);
this.customerNumber = number;
}
public void setCustomerNumber(String number){
this.customerNumber = number;
}
public String getCustomerNumber(){
return customerNumber;
}
#Override
public String toString(){
String name = super.toString();
return name + "\n" + "CustomerNumber: " + customerNumber;
}
}
Employee.java
package pkg8.pkg2.person.manager;
/**
*
* #author Zachary
*/
public class Employee extends Person {
private String ssn;
public Employee(String first, String last, String ssn){
super(first, last);
this.ssn = ssn;
}
public String getSsn(){
return "xxx-xx-" + ssn.substring(ssn.length() - 4);
}
public void setSsn(String ssn){
this.ssn = ssn;
}
#Override
public String toString() {
String name = super.toString();
return name + "\n" + "SSN: " + getSsn();
}
}
Console.java
package pkg8.pkg2.person.manager;
import java.util.*;
/**
*
* #author Zachary
*/
public class Console {
private static Scanner sc = new Scanner(System.in);
public static String getString(String prompt) {
String s = "";
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
s = sc.nextLine();
if (s.equals("")) {
System.out.println("Error! This entry is required. Try again.");
} else {
isValid = true;
}
}
return s;
}
public static String getString(String prompt, String s1, String s2) {
String s = "";
boolean isValid = false;
while (!isValid) {
s = getString(prompt);
if (!s.equalsIgnoreCase(s1) && !s.equalsIgnoreCase(s2)) {
System.out.println("Error! Entry must be '" + s1 + "' or '" +
s2 + "'. Try again.");
} else {
isValid = true;
}
}
return s;
}
public static int getInt(String prompt) {
int i = 0;
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
isValid = true;
} else {
System.out.println("Error! Invalid integer. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(String prompt, int min, int max) {
int i = 0;
boolean isValid = false;
while (!isValid) {
i = getInt(prompt);
if (i <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (i >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return i;
}
public static double getDouble(String prompt) {
double d = 0;
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid number. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static double getDouble(String prompt, double min, double max) {
double d = 0;
boolean isValid = false;
while (!isValid) {
d = getDouble(prompt);
if (d <= min) {
System.out.println(
"Error! Number must be greater than " + min + ".");
} else if (d >= max) {
System.out.println(
"Error! Number must be less than " + max + ".");
} else {
isValid = true;
}
}
return d;
}
}
I understand that it is a conflicting package I just don't know how to fix it.
Any help would be greatly appreciated.
If you read the documentation, then you'll find that the javadoc of getName() states:
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by The Java™ Language Specification.
JLS 13.1. The Form of a Binary says:
The class or interface must be named by its binary name, which must meet the following constraints:
The binary name of a top level type (§7.6) is its canonical name (§6.7).
JLS 6.7. Fully Qualified Names and Canonical Names says:
For every primitive type, named package, top level class, and top level interface, the canonical name is the same as the fully qualified name.
The fully qualified name of a top level class or top level interface that is declared in a named package consists of the fully qualified name of the package, followed by ".", followed by the simple name of the class or interface.
In summary: getName() returns the fully qualified name of the class.
If you don't want that, call getSimpleName().

while loop accumulator in java

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;
}
}

Java GPA CALC issue

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.

Cannot figure out how to print toString

package homeWork;
public class ShoppingBag {
private int items;
private float totalRetailCost;
private float taxRate;
public ShoppingBag(float taxRate){
this.taxRate = taxRate;
items = 0;
totalRetailCost = 0.0f;
}
// Transformer
public void place(int numItems, float theCost){
items = items += numItems;
totalRetailCost += (numItems * theCost);
}
public int getItems(){
return items;
}
public float getRetailCost(){
return totalRetailCost;
}
public float getTotalCost(){
return totalRetailCost + (1 + taxRate);
}
public String toString(){
String result = "The bag contains " + items + " items";
result += "The retail cost of items is" + totalRetailCost;
result += "The total cost = " + getTotalCost();
return result;
}
}
package homeWork;
import java.util.*;
public class MainClass {
public static void main(String[] args){
Scanner conIn = new Scanner(System.in);
ShoppingBag sb = new ShoppingBag(0.06f);
int count = 0;
float cost = 0.0f;
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
while(count != 0){
System.out.print("Enter cost: ");
cost = conIn.nextFloat();
sb.place(count, cost);
System.out.print("Enter count (0 to stop):");
count = conIn.nextInt();
}
}
}
I have tried all that I have found on here to return result after completion of input. Ive done what my book has shown me to do but I am not getting a result. Just a nudge in the right direction would be helpful.
You are no printing the object anywhere. Print the object
System.out.print(sb);

Categories