Java - object can't store data - java

My dad and I narrowed it down to the object can't store the data. also, I'm new to java. The code is supposed to print in the console the first name, last name, grade, and grade average. I think the problem is in public double getCalcGraeAverage() but correct me if wrong, please.
import java.util.Scanner;
/**
* Write a description of class Student here.
*
* #author XXXX
* #version XXXX
*/
public class Student
{
String firstName;
String lastName;
int gradeLevel;
double gradeAverage;
int totalAssignments;
double totalPoints;
/**
* Create a new student with student's name, grade, and average
*/
public Student(String newFirstName, String newLastName, int newGradeLevel, double newGradeAverage)
{
firstName = newFirstName;
lastName = newLastName;
gradeLevel = newGradeLevel;
gradeAverage = newGradeAverage = 0.0;
}
/**
* Return the student's first name.
*/
public String getFirstName()
{
return firstName;
}
/**
* Return the student's last name.
*/
public String getLastName()
{
return lastName;
}
/**
* Return the grade level of the student.
*/
public int getGradeLevel()
{
return gradeLevel;
}
/**
* Calculates grade average.
*/
public double getCalcGradeAverage()
{
double gradeAverage = totalAssignments / totalPoints;
return gradeAverage;
}
public static void main (String[] args)
{
Student student1 = new Student ("XXXX", "XXXX", 11, 0.0);
System.out.println("The student's first name is: " + student1.getFirstName());
System.out.println("The student's last name is: " + student1.getLastName());
System.out.println("The student's grade level is: " + student1.getGradeLevel());
System.out.println("Please enter the total assignment points the student has earned: ");
Scanner input = new Scanner(System.in);
Double totalAssignments = input.nextDouble();
System.out.println("Please enter the number of assignments given: ");
double totalpoints = input.nextDouble();
System.out.println(student1.getFirstName() + " " + student1.getLastName() + " average grade is" + student1.getCalcGradeAverage());
}
}

In your code you are :
creating a Student student1 object
reading totalAssignments, totalpoints from System.in
calling student1.getCalcGradeAverage()
between steps 2 and 3 you have to set the fields totalAssignments, totalpoints of student to the values you read or they will retain their default values of zero. E.g.
student1.totalAssignments = totalAssignments;
student1.totalpoints = totalpoints;
Also, since totalAssignments is of type int, you probably want to read it as:
int totalAssignments = input.nextInt();

When writing your code, you declare variables for the student class with class scope.
int totalAssignments;
double totalPoints;
those class scope variable are used in the method :getCalcGradeAverage()
totalAssignments of Student and totalPoints of student are used in this method
When you create a new Student those variable are equals to zero because not affected by a value in your constructor.
in the main method when you writes :
Double totalAssignments =
you declare a new variable named "totalAssignments" with a method scope.When the method ends, the variable reference goes away and there is no way to access that variable any longer.
you can consider that the variable decalred is not the same that the student variable: student.totalAssignments is always equals to zero because no value affected to him.
Then assuming that you can do that :
student1.totalAssignments = input.nextInt();
student1.totalPoints = input.nextDouble();

Related

Creating an employee class and emplyoee class demo?

We have to use set and get methods to such as
Employee()
Employee(empId:int)
Employee(empId:int, payRate:double, weeklyHrs:double)
setId(empId:int):void
setPayRate(payRate:double):void
setHrs(weeklyHrs:double):void
getId():int
getPayRate():double
getHrs():double
getWeeklyPay():double
toString():String
to create an employee class and employee class demo. We have to use two employee id's and type in their weekly hours and pay to return how much they made. Here is what I have down for the Employee class:
//#param
Scanner input = new Scanner(System.in); //Scanner object
public void setID(int empID){
System.out.println("Enter employee 1's id: ");
String input2 = input.next();
int emp1 = Integer.parseInt(input2);
System.out.println("Enter employee 2's id: ");
String input3 = input.next();
int emp2 = Integer.parseInt(input3);
}
//#param
public void setPayRate(double payRate){
System.out.println("Enter employee 1's payrate: ");
String input4 = input.next();
double pay1 = Double.parseDouble(input4);
System.out.println("Enter employee 2's payrate: ");
String input5 = input.next();
double pay2 = Double.parseDouble(input5);
}
//#param
public void setHrs(double weeklyHrs){
System.out.println("Enter employee 1's hours: ");
String input6 = input.next();
double hour1 = Double.parseDouble(input6);
System.out.println("Enter employee 2's hours: ");
String input7 = input.next();
double hour2 = Double.parseDouble(input7);
}
//GET METHODS
public int getID(int empID){
return empID;
}
public double getHrs(double hours){
return hours;
}
public double getWeeklyPay(double pay){
return pay;
}
//DISPLAY ANSWERS
public String toString(int emp1,int emp2,double hour1,double hour2,double pay1,double pay2){
String myString= String.format("The first employee's ID is: " + emp1 +
"The second employee's ID is: " + emp2 +
"The first employee's hours are: " + hour1 +
"The secondemployee's hours are: " + hour2 +
"The first employee's pay: $%,.2f"+ pay1*hour1 +
"The second employee's pay: $%,.2f" + pay2*hour2,
emp1,emp2,hour1,hour2,pay1,pay2);
return myString;
}
}//End of class
I'm just wondering what I would put in my Employee Class Demo so that it would be able to return the toString method?
System.out.println() calls the toString() method automatically on any object you pass into it - alternatively, you can just call it yourself:
Employee e;
// properly initialize e
System.out.println(e); // works
System.out.println(e.toString()); // also works
As a side note, your toString() method is incorrect. It should be a member function of the Employee class - making it a method that takes Employee objects is the wrong way to do it (assuming you want to follow standard Java OOP practices).
The proper method would look something like this:
// Notice no arguments are passed in
public String toString() {
// Instead, we use the "this" variable
return String.format("My ID is %s, my hours are %f, and my pay is $%,.2f", this.empID, this.hours, this.pay);
}

Add a second class to the main class for an annual compensation calculator

I tried searching for this answer and found several answers that were similar to what I am looking for, but I can't seem to apply the suggestions provided on unrelated data to my specific program.
I need to take this working code I have created (a program to calculate an employee's annual compensation) and adjust it in a way that shows two classes (per the instructions of my homework assignment). The output given is exactly what I want, I just need help to reorganize the code so there is more than the main class. Is this something I can get help with here?
Here is my working code:
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
double commissionPercentage = 0.06;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
double totalCompensation = (value * commissionPercentage) + salary;
System.out.println("Your annual compensation is: " + "$" + totalCompensation);
}
}
Thanks in advance.
create a class Employee with salary and commissionPercentage as the fields.
In constructor take the salary and commision% of employee and initate the fields.
in this class Employee create a method which will take vavlue as input and will calculate the compensation and return it.
So from main create the instance of Employee class and call the calculateMethod.
I would structure it with these classes:
AnnualCompensationCalculator which will do the computation for you as a utility class, and
AnnualCompensation main class which would be focused on requesting for the user input (and would call the calculator).
Suppose you can move the logic inside new class.
AnnualCompensationCalculator.java
public class AnnualCompensationCalculator{
private static double commissionPercentage = 0.06;
public static double calculateCompensation(double sales ,double salary){
return((sales * commissionPercentage) + salary);
}
}
AnnualCompensation .java
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
System.out.println("Your annual compensation is: " + "$" + AnnualCompensationCalculator.calculateCompensation(value,salary));
}
}
Following Object Oriented Programming, I suggest you create a new class Employee that holds the salary and compensation percentage of an employee, which also has a method for calculating the compensation.
Like this:
class Employee {
private double salary;
private double commPercent;
public Employee(double salary, double commPercent) {
this.salary = salary;
this.commPercent = commPercent;
}
public double calculateCompensation(double totalSales) {
return (totalSales * commPercent) + salary;
}
/* Setters & Getters */
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getCommPercent() {
return commPercent;
}
public void setCommPercent(double commPercent) {
this.commPercent = commPercent;
}
}
Then have your main class use this Employee class to do all the work:
public class AnnualCompensation {
public static void main(String[] args) {
//Initialize an Employee object
Employee emp = new Employee(60000, 0.06);
//Create command output for the user to get directions to enter value
System.out.print("Enter total amount of sales for the year: ");
Scanner input = new Scanner(System.in);
double salesAmt = input.nextDouble();
//Calculate the compensation based on the user input then print it
System.out.println("Your annual compensation is: $"
+ emp.calculateCompensation(salesAmt));
}
}

How to fix my counter and average calculator

I have to create a code that takes user input for grades based on a students name that the user has inputted.
The input is to stop when a number less than 0 is inputted and the output should be the student name, the total of all the scores, and the average score.
For some reason I cannot get the average or the total to print, and my counter in my student class is showing an error "remove this token '++'"
Here is my main class, and my student class :
/**
* COSC 210-001 Assignment 2
* Prog2.java
*
* description
*
* #author Tristan Shumaker
*/
import java.util.Scanner;
public class main {
public static void main( String[] args) {
double[] addQuiz = new double[99];
int counter = 0;
//Creates new scanner for input
Scanner in = new Scanner( System.in);
//Prompts the user for the student name
System.out.print("Enter Student Name: ");
String name = in.nextLine();
// requests first score and primes loop
System.out.print("Enter Student Score: ");
int scoreInput = in.nextInt();
while( scoreInput >= 0 ) {
System.out.print("Enter Student Score: ");
scoreInput = in.nextInt();
counter++;
}
System.out.println( );
System.out.println("Student name: " + name);
System.out.printf( "\nAverage: %1.2f", total(addQuiz, counter) );
System.out.printf( "\nAverage: %1.2f", average(addQuiz, counter) );
}
}
and my student class:
public class Student {
private String name;
private int total;
private int counter;
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void addQuiz( int scoreInput) {
total += scoreInput;
int counter++;
}
public static double average( double[] addQuiz, int counter ) {
double sum = 0;
for( int t = 0; t < counter; t++) {
sum += addQuiz[t];
}
return (double) sum / counter;
}
}
Any help you guys are able to give would be greatly appreciated, thanks in advanced.
change int counter++; in the addQuiz() method to just counter++;, as otherwise you're trying to declare a variable with identifier counter++ which is not a valid identifier. Also since you've declared average() to be a static method on the Student class you'll need to call it like so:
Student.average(addQuiz, counter);
I'm not seeing a definition for total() in your code so I don't know if the same would apply to that.
EDIT
To answer why average() is returning zero, it looks like you never set any values in the addQuiz double array that you're passing in, so it will contain all zeros, and as a result sum will be 0. I think what you want to do is to change your while loop in the main method to put the scoreInput value in the array at the counter index like so:
while( scoreInput >= 0 ) {
System.out.print("Enter Student Score: ");
scoreInput = in.nextInt();
addQuiz[counter] = scoreInput;
counter++;
}
In your main class you are not using your Student class at all.
Consider doing
Student student = new Student (name);
and then using the methods such as
student.addQuiz (scoreInput);
and later
student.getTotal ();
etc.
You also do not need to store the variable counter in the Student Object at all as it is being passed as a parameter.

Why does this array go out of bounds inconsistently?

This is a Student class I have which creates a student that has a name, grade, and ID number. The Student is used as the key in a TreeMap, while the student's grade is used as the value. I wrote compareTo as I am implementing Comparable, but this error pops up upon entering in the first student:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Student.<init>(Student.java:25)
at Main.main(Main.java:50)
Java Result: 1
I think it is coming from the splitting of the student's name into a String[], but I've tested those lines that call the first and last names, as well as the line that splits the name and they all seem to work as intended, except for when they are called in compareTo.
Any help would be much appreciated.
public class Student implements Comparable<Student>{
private String name, grade, first, last;
private String[] stuName;
private int id;
/**
* Constructs a new Student with a name, ID Number, and a grade.
* #param n name
* #param i ID Number
* #param g grade
*/
public Student(String n, int i, String g){
name = n;
id = i;
grade = g;
stuName = n.split(" ");
first = stuName[0];
last = stuName[1];
}
/**
* Compares Students. First by last name, then by first if the last names
* are the same. If the first names are also the same, the students are
* compared by their ID Numbers.
* #return the value upon comparing the proper property of the Student
*/
#Override
public int compareTo(Student other){
if (last.equals(other.getLast())){
if (first.equals(other.getFirst())){
return id - other.getID();
}else
return first.compareTo(other.getFirst());
}
return last.compareTo(other.getLast());
}
/**
* Changes the student's current grade.
* #param g new grade
*/
public void changeGrade(String g){
grade = g;
}
/**
* Returns student's name.
* #return name
*/
public String getName(){
return name;
}
/**
* Returns student's first name.
* #return first name
*/
public String getFirst(){
return first;
}
/**
* Returns student's last name.
* #return last name
*/
public String getLast(){
return last;
}
/**
* Returns the student's grade.
* #return grade
*/
public String getGrade(){
return grade;
}
/**
* Returns the student's ID Number
* #return id number
*/
public int getID(){
return id;
}
Tester:
public class Main {
public static void main(String[] args) throws InterruptedException{
Map<Student, String> students = new TreeMap();
Scanner in = new Scanner(System.in);
System.out.println("How many students do you want to add?");
int numStudents = in.nextInt();
String name, grade;
int id;
for (int i = 1; i < numStudents; i++){
System.out.println("Name of student " + i + "?");
name = in.nextLine();
in.nextLine();
System.out.println("Grade of " + i + "?");
grade = in.nextLine();
System.out.println("ID Number of " + i + "?");
id = in.nextInt();
Student s = new Student(name, id, grade);
students.put(s, s.getGrade());
}
System.out.println("How many students do want to remove");
int remStudents = in.nextInt();
for (int i = 0; i < remStudents; i++){
System.out.println("ID?");
int remID = in.nextInt();
for (Student s : students.keySet()){
if (s.getID() == remID){
students.remove(s);
}
}
}
System.out.println("How many grades do you want to change?");
int changeGrades = in.nextInt();
for (int i = 0; i < changeGrades; i++){
System.out.println("ID?");
int foo = in.nextInt();
System.out.println("New grade?");
String newGrade = in.nextLine();
for (Student s : students.keySet()){
if (s.getID() == foo){
s.changeGrade(newGrade);
}
}
}
String printout = "";
for (Student s : students.keySet()){
printout += s.getLast() + ", " + s.getFirst() + " (" + s.getID() + "): " + s.getGrade() + "\n";
}
System.out.println(printout);
}
}
Probably because you have two different loops, with different indices:
in your one loop, you start from 1, and thus you are 1 student short:
for (int i = 1; i < numStudents; i++){
in the delete loop you have a 0-based index:
for (int i = 0; i < remStudents; i++){
I suspect that, you think you add 2 studends, but really you have just one (at index 0), and thus your indexout-of-bounds exception.
EDIT, OP has added a 'full' stack for the exception, and the above answer is not related to the OP's problem.....
Answer 2: Based on your revised stack/exception edit, the only possible answer is that there are no spaces in the student's name..... your assertion that there is always a space is simply not true ....
you may want to add a count qualifiewr to the split so that you will get an empty string on any invalid input:
stuName = n.split(" ", 2);

How do I allow a variable to be used by various functions? java

I have tried various suggestions already given on the website.. But honestly i couldnt find something to fix it.
Basically when i try to use any variable created in Accept... it cant be used in other functions. Is there a simple solution to fix this? (Without changing the main code)
import java.util.Scanner;
class x4Salary
{
Scanner input = new Scanner(System.in);
public void accept()
{
System.out.println("Please input the name of the teacher");
String name = input.next();
System.out.println("Please input the address ");
String adress = input.next();
System.out.println("Please input the phone number");
long num = input.nextLong();
System.out.println("Please input the subject specialization");
String subjectSpecialization = input.next();
String subS = subjectSpecialization;
System.out.println("Please input the Monthly Salary");
long sal = input.nextLong();
if(sal>175000)
{
tax();
}
display();
double tax = 0.0;
}
public void tax()
{
System.out.println("Your current salary is : " + sal);
tax = sal + ((5/sal)*100);
System.out.println("The salary + Tax : " +tax);
display();
}
public void display()
{
System.out.println("The name of the teacher : " + name);
System.out.println("The Address of the teacher :" +adress);
System.out.println("The Phone number of the Teacher: "+num);
System.out.println("The Subject Specialization of the Teacher" + subS);
System.out.println("The Monthly salary of the teacher" +sal + tax);
}
}
You can make those variables as class members
class x4Salary
{
protected String name, address; //and so on
and then instead of String name = input.next();
name = input.next();
name would be visible in all methods of X4Salary
Those variables are scoped to the method alone. If you want to retain those values entered your options are:
create member variables in the containing class and populate those. Those values would be available for the lifetime of that class
return the values from the method. Since you have multiple values you would likely want an object containing these values to be returned
call another object from within that method, and pass the data that way.
For option 2 you could define a return object thus:
class Teacher {
private String name;
private String phone;
// add appropriate constructor
}
I suspect Teacher is a key object in your application and you would likely want to add the method display() to the Teacher class itself. Remember that OO is about creating objects and getting them to do things for you, not handling discrete related variables yourself.
you cant use the local variables(variables defined inside your method) outside of that method. they are only confined to that method. you either have to make it an instance variable or return that variable so that the other methods can use it.
in your case.
if you want to use sal outside method accept . make it an instance variable.
Class classname {
public long sal;
public void accept(){
//can access sal here
sal = input.nextLong();
}
public void display(){
//cvan access sal here
}
}
Define your variables as Member Variables in the Class then it can be accessible in all the member methods.
import java.util.Scanner;
class x4Salary
{
private double tax=0.0;
private string name, adress, subS;
private long num, sal;
Scanner input = new Scanner(System.in);
public void accept()
{
System.out.println("Please input the name of the teacher");
name = input.next();
System.out.println("Please input the address ");
adress = input.next();
System.out.println("Please input the phone number");
num = input.nextLong();
System.out.println("Please input the subject specialization");
subS = input.next();
System.out.println("Please input the Monthly Salary");
sal = input.nextLong();
if(sal>175000)
{
tax();
}
display();
}
public void tax()
{
System.out.println("Your current salary is : " + sal);
tax = sal + ((5/sal)*100);
System.out.println("The salary + Tax : " +tax);
display();
}
public void display()
{
System.out.println("The name of the teacher : " + name);
System.out.println("The Address of the teacher :" +adress);
System.out.println("The Phone number of the Teacher: "+num);
System.out.println("The Subject Specialization of the Teacher" + subS);
System.out.println("The Monthly salary of the teacher" +sal + tax);
}
}
You would need to make those variables as instance variables.
The variables created in a method, in confined to that method scope only. It is not visible outside that method. It will be created when the method is invoked, and then when the method is finished with execution, that variable becomes eligible for Garbage Collection.
This is true for any block scope you have. The variables created in one block, will not be visible outside that block.
For e.g: -
{ // A block
int num = 10;
}
System.out.println(num); // Error. num not visible here.
So, to access the variable in all methods, declare it as: -
public class Demo {
private int num; // Instance variable declaration. Outside every method.
public void setNum(int num) {
this.num = num;
}
public int getNum() {
return this.num;
}
}
So, as you can see, variable num is used in both the methods: - setNum and getNum.
Go to this tutorial to get started with classes, objects, and member declarations: -
http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

Categories