Java error in my 2nd class - java

I have 2 classes. 1 class sets & gets a students' name, 3 test scores for a student & an average for the 3 scores. The other class has a main method to set and get this information. I'm getting an error from my IDE for the 2nd class only.
public class Student5th
{ /**
Instance variables
Each student object will have a name and three test scores
*/
private String name; //Student name
private int test1; //Score on test 1
private int test2; //Score on test 2
private int test3; //Score on test 3
/**
Set a student's name
Preconditions -- nm is not empty
Postconditions -- name has been set to name
*/
public void setName (String nm)
{
name = nm;
}
/** Get a student's name
Preconditions -- none
Postconditions -- returns the name
*/
public String getName ()
{
return name;
}
/** Set the score on the indicated test
Preconditions -- 1 <= i <= 3
-- 0 <= score <= 100
Postconditions -- test i has been set to score
*/
public void setScore (int i, int score)
{
if (i == 1) test1 = score;
else if (i == 2) test2 = score;
else test3 = score;
}
/** Get the score on the indicated test
* Preconditions -- none
* Postconditions -- returns the score on test I
* */
public int getScore (int i)
{
if (i == 1) return test1;
else if (i == 2) return test2;
else return test3;
}
/** Compute and return a student's average
* Preconditions -- none
* Postconditions -- returns the average of the test scores
* */
public int getAverage() {
int average;
average = (int) Math.round((test1 + test2 + test3) / 3.0);
return average;
}
}
My 2nd class with the main method...
import java.util.*;
public class TestStudent
{
public static void main (String[] args)
{
Scanner console = new Scanner(System.in);
private Student **student1**;
private Student **student2**;
String s;
int t;
student1 = new Student();
student2 = new Student();
s = console.next();
student1.setName (s);
t = console.nextInt();
student1.setScore (1, t);
student1.setScore (2, console.nextInt());
student1.setScore (3, console.nextInt());
student2.setName (**keyboard**.readLine());
student2.setScore (1, console.nextInt());
student2.setScore (2, console.nextInt());
student2.setScore (3, console.nextInt());
}
}
I've bolded (well, put double asterisks around) the parts which are giving me errors. I'm close to getting this program to work, but I don't know why my IDE is giving me problems for student1 & student2 in the 2nd class, as well as giving me a problem for (keyboard.readLine()); for student2.setName in the 2nd class?

You shouldn't specify an access level modifier (like private or public) inside a method:
Student student1; // delete 'private'
Student student2; // delete 'private'
Why? Because if you declare a variable inside a method, it should only be visible inside that specific method. It doesn't make sense to declare it as private, public or protected.
You could take a look to this article about Information hiding.

A few things going on here.
If your lecturer specified that student1 and student2 must be private, then he intended them to fields of the class. That means you have to declare them outside of the method. Move these two declarations up, to before the line that says public static void main ....
Also, your class is called Student5th, but you're using it within TestStudent as if it were just Student. The class name used in the variable declarations has to match the actual name of the class.
Where you wrote keyboard.readLine() towards the end, you actually meant to write ccnsole.nextLine(). You shouldn't be trying to read the same input stream with two different objects at the same time.
If you do change keyboard.readLine() to console.nextLine(), then you'll need an extra call to console.nextLine() immediately before it, to consume the newline character at the end of the line that has the first student's third score.

Related

Elegant way to add a value to a class variable in java

I have a class say Student
public class Student {
private String name;
private int score;
}
Assume I have all getter/setters.
Currently, I have an object of the student class say std which is having score value as 50.
I want to add 10 to the score in this object.
I can do this by below code:
std.setScore(std.getScore() + 10);
I am looking for an elegant way to write the same in which I don't use both getter and setter and can just increment the score by 10 or even by 1.
Say by using ++ or something like +=10 etc.
Write a method:
public void incrementScore(int amount) {
score += amount;
}
Is a negative increment allowed? If not, check it:
/**
* Increments the score by the given amount.
*
* #param amount the amount to increment the score by; must not be negative
* #throws IllegalArgumentException if the amount is negative
*/
public void incrementScore(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("The increment must not be negative.");
}
score += amount;
}
This approach is more elegant than using get/set because:
it allows you to check the argument agains business rules,
it adds a business method with a name that reveals intention.
it allows you to write JavaDoc comments that describe the exact behaviour of the operation
As sugested in the comments you can create a new method on the student class.
public class Student {
private String name;
private int score;
public void incrementScore(int increment){
this.score = this.score + increment;
}
}
And then call it on the std instance:
std.incrementScore(10)

How to set a variable as a class method and not as a static method

I'm trying to grasp some comments that were made to me by my professor on a programming assignment. The assignment was to write a program that calls upon another class. This program was to take 2 investors with different starting balances and show how much interest they would collect after a 15 month period.
Just so everyone is clear, my assignment has already been graded, so any critiques or changes would NOT be helping me complete my homework, but ONLY to help me understand what I did wrong and how I can fix it for future assignments. I received a 90% on my program for my grade.
The following comments were made about my assignment:
"Your setInterest method was to be a class method not an instance
method. Also, your call should have been
IWUnit4Ch13Investor.setInterest(rate);"
I'm not exactly following what I did wrong or how I can fix it. Can someone please show me what I did wrong and possibly explain why it's wrong so that I may correct my habits for future assignments and grasp how to correctly write code?
// IWUnit4Ch13.java
import java.util.*;
import java.util.Scanner;
// main class
public class IWUnit4Ch13 {
public static void main(String[] args) {
// Declares local variables
double rate, INTEREST_RATE;
// Instantiate investor1 & investor2 objects using a two parameter constructor
IWUnit4Ch13Investor investor1 = new IWUnit4Ch13Investor(1001, 2000);
IWUnit4Ch13Investor investor2 = new IWUnit4Ch13Investor(2001, 4000);
Scanner input = new Scanner(System.in);
// Receives the APR by the user
System.out.print("Please enter the APR in the form of .05 for 5%: ");
rate = input.nextDouble();
// Moves the decimal 2 places to the left (used later)
INTEREST_RATE = rate * 100;
// Sets the interest rate using a class variable
investor1.setInterestRate(rate);
investor2.setInterestRate(rate);
// Prints the header for the table
System.out.printf("Monthly balances for one year with %.2f annual interest:\n\n", rate);
System.out.println("Month Account # Balance Account # Balance");
System.out.println("----- --------- ------- --------- -------");
// Loop that prints each month on the table
// Uses class variables to add interest and get balance for display
for (int i = 1; i <= 15; i++) {
investor1.addInterest();
investor2.addInterest();
System.out.printf("%5d %9d %9.2f %9d %9.2f\n", i, investor1.getACCOUNT_NUMBER(), investor1.getBalance(), investor2.getACCOUNT_NUMBER(), investor2.getBalance());
}
// Prints the calculated interest earned by both investors
System.out.printf("\nInvestor1 earned : %.2f", investor1.getInterest());
System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
System.out.print("%\n");
System.out.printf("Investor2 earned : %.2f", investor2.getInterest());
System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
System.out.print("%\n\n");
} // end of internal main
} // end of main class
// Creates IWUnit4Ch13Investor.java which is used in IWUnit4Ch13.java
public class IWUnit4Ch13Investor extends IWUnit4Ch13 {
// All variables are declared private
private static double interestRate; // class variable
private final int ACCOUNT_NUMBER; // declare constant ACCOUNT_NUMBER
private double balance; // instance variable called balance
private double initialBalance; // to hold the initial balance
private double interest; // to count how much interest was made
private double INTEREST_RATE; // used to convert the float interestRate to int
// Two parameter constructor to initialize account number and balance
public IWUnit4Ch13Investor(int acctNum, double initialBalance) {
this.initialBalance = initialBalance;
this.ACCOUNT_NUMBER = acctNum;
balance = initialBalance;
}
// To return the balance to parent
public double getBalance() {
return balance;
}
// Class method to set the annual interest rate
public void setInterestRate(double rate) {
interestRate = rate;
}
// Method to add interest based on balance * interestRate / 12
public void addInterest() {
balance += balance * interestRate/12.0;
}
// To get account number in parent
public int getACCOUNT_NUMBER() {
return ACCOUNT_NUMBER;
}
// Used to get the amount of interested earned during 15 months
public double getInterest() {
interest = balance - initialBalance;
return interest;
}
} // end of class
Thank you all in advance for your help.
Terms
First of, please don't confuse terms. A variable is different to a method:
// A class
public class Dog {
// Member variable
private String name;
// Method
public void bark() {
// Variable
String textToBark = "Wuff";
// Call to a method
System.out.println(textToBark);
}
}
Elsewhere:
// Creating a new instance of class "Dog"
// and saving a reference to it inside a variable
Dog bello = new Dog("Bello");
Explanation
Your teacher said he wants the setInterest to be a class method instead of an instance method. What he wants to say with that is that it should be declared static and thus not belonging to instances of the class but to the class itself. Here is more on what static means for methods: Java: when to use static methods
Solution
So the method should look like this:
// Method to set the annual interest rate
public static void setInterestRate(double rate) {
IWUnit4Ch13Investor.interestRate = rate;
}
Where interestRate then also needs to be declared static (which you already did):
// To count how much interest was made
private static double interestRate;
To indicate the access of static variables one should add the class name before, so instead write it like this:
// Method to add interest based on balance * interestRate / 12
public void addInterest() {
balance += balance * IWUnit4Ch13Investor.interestRate / 12.0;
}
The same holds for calling static methods, instead of
investor1.setInterestRate(rate);
investor2.setInterestRate(rate);
do this
IWUnit4Ch13Investor.setInterestRate(rate);
Due to the nature of static you then also need to set this only once since static variables are shared by all instances of that class.
So a static variable is shared by all instances of the class.
If you want all investors to be forced to share the same interest rate, use a static variable.
Methods that only affect static variables should (https://www.ietf.org/rfc/rfc2119.txt) be declared static:
public static void setInterestRate(double rate) {
interestRate = rate;
}
private static double interestRate;
You would then call the static method by specifying the class name, not the instance variable. Note that you can call the static method before you even have any instances of the class, and you only need to call it once:
Investor.setInterestRate(0.05);
Investor i1 = new Investor();
Investor i2 = new Investor();
double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();
If you want each investor to be able to have different interest rates, do not use a static variable, use a member variable and method:
public void setInterestRate(double rate) {
interestRate = rate;
}
private double interestRate;
You then call the method by specifying the instance variable:
Investor i1 = new Investor();
Investor i2 = new Investor();
i1.setInterestRate(0.04);
i2.setInterestRate(0.06);
double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();
Also, none of that really matters because the output is wrong:
double monthly_rate = pow(10.0, log10(1.0 + yearly_rate) / 12.0) - 1.0;
The system shall not fail

Creating Methods and Classes (Java)

I am trying to write a class called Student that is supposed to work with a StudentDriver. However, I am having a very hard time wrapping my head around the concept of methods and classes. I do not know how to receive and return data. Moreover, I don't even know if I am declaring my data correctly. Please help me. I would greatly appreciate it.
Also when I compiled the Student it says that it cannot find the symbol this.setGPA. How so? When in the driver it has .setGPA.
Thank you.
// This will be the "driver" class for the Student class created in
// MinilabWritingClasses (It looks very complicated because of all
// the comments, but it really just creates instances of Student and
// tells them to do things...)
public class StudentDriver
{
public static void main(String[ ] args)
{
//create an instance of Student
System.out.println("***** Creating a Student, calling the default constructor");
Student stud1 = new Student();
//print it so we can see what the default values were for the class data
//note that its toString() will be called automatically
System.out.println("\n***** printing it - notice the default values (set by Java)");
System.out.println(stud1);
//create another instance of a Student, passing in initial values to its constructor
System.out.println("\n***** Creating another Student, passing initial values to its constructor");
Student msBoss = new Student("Bill Gates", 56, 'm', 3.2, true);
//tell it to return its age
System.out.println("\n***** telling it to return its age.");
int theAge = msBoss.getAge();
System.out.println("Its age is: " + theAge);
//print it - note that its toString() will be called automatically;
System.out.println("\n***** printing it - see if values are correct");
System.out.println(msBoss);
//ask it if it is on probation
System.out.println("\n***** asking it if it is on probation (check answer)");
System.out.println("onProbation() returned: " + msBoss.onProbation());
//tell it to change its gpa to 1.3
System.out.println("\n***** telling it to change its gpa to 1.3");
msBoss.setGPA(1.3);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolean boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//tell it to complain
System.out.println("\n***** telling it to complain");
System.out.println("complain() returned: " + msBoss.complain());
//tell it to change its onScholarship field to false
System.out.println("\n***** telling it to change its onScholarship field to false");
msBoss.setOnScholarship(false);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//create a different student, tell it to have some different values, and tell it to print itself
System.out.println("\n***** creating a different Student, passing initial values to its constructor");
Student stud2;
stud2 = new Student("Hillary Clinton", 64, 'f', 2.0, true); //notice-can define variable and create it in 2 steps
//print it
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(stud2);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = stud2.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
}
}
Here is the class that I am writing.
public class Student
{
private String name;
private int age;
private char gender;
private double gpa;
private boolean onScholarship;
public Student()
{
}
public Student(String newName, int newAge, char newGender, double newGPA, boolean newScholarship)
{
this.name = newName;
this.age = newAge;
this.gender = newGender;
this.gpa = newGPA;
this.onScholarship = newScholarship;
}
public int getAge(int newAge)
{
return age;
}
public double setGPA (double newGPA)
{
this.setGPA = newGPA;
}
public boolean setOnScholarship (boolean newScholarship)
{
this.setOnScholarship = newScholarship;
}
public String toString()
{
return this.name + "\t" + this.age + "\t" + this.gender + "\t" + this.setGPA + "\t" + this.setOnScholarship;
}
public boolean onProbation()
{
if (onScholarship==true && gpa < 2.0)
return true;
else
return false;
}
}
Try to change this line:
this.setGPA = newGPA;
to this:
this.gpa = newGPA;
setGPA symbol not found is because there is no setGPA field (it is a method). You are trying to change the gpa field.
You also don't need the empty public Student() {} constructor -- this is automatically created by Java.
Also, as #Sam pointed out, since setOnScholarship() doesn't return anything, you can change the return type boolean to void. This is because there is no return statement, and this returning of nothing is a void type.
Overall, though, you have a good understanding on creating instances of another class (i.e., creating Students).
On request (although it doesn't have much to do with your code), here is a brief summary on static.
The static keyword is used with methods and fields that are not used with an instance of that class, but the class itself.
For example, in your case, pretty much all of the Student fields and methods are non-static, because they are properties of Student objects:
this.gpa;
this.setGpa();
On the other hand, if it were not changing a variable related to a single object, for example the total number of students, you could create a static field in Student:
public class Student {
// non-static fields for each instance
public double gpa;
// static field for the class
public static numStudents;
public Student() {
// create student by setting object (non-static) fields, for example...
this.gpa = 3.2;
// edit static variable
numStudents++; // notice how there is no `this` keyword - this changes a static variable
}
}
... and from StudentDriver, numStudents can be retreived with:
Student.numStudents; // notice how this is like `this.[property]`, but with the class name (Student) - it is an instance of the class
I hope this helps! OOP programming is a difficult topic that can't be explained so simply.

Trouble passing parameters to an object java

I'm having trouble passing parameters to specify a specific attributes to an object to change that attribute. I'm a little new to objects and how they work. I need to use objects for this, as it's an assignment.
The purpose of this program is to basically store grades in an electronic gradebook. However, I have an object filled with names and quiz grades of hypothetical students. I need to create the setQuiz() method to grab a specified quiz value of the specified student, and then change it to specified grade. Here's what I have so far.
public class Student extends TestStudent
{
public String name;
public int q1, q2, q3, q4, q5;
public Student(String cName, int cq1, int cq2, int cq3, int cq4, int cq5 )
{
name = cName;
q1 = cq1;
q2 = cq2;
q3 = cq3;
q4 = cq4;
q5 = cq5;
}
public void setQuiz(int grade, int quiz, int student)
{
super.studentAr[student].{quiz?} = grade;
//Basically, I am not sure how to reference the exact grade I need
//to access, thus the question mark.
}
}
So what do I do, StackOverflow? Do I need to totally rethink my structure here? Is it bad practice? Or am I on the right track and just missing something vital?
Thanks a bunch in advance.
With this structure, the only way you can access each quiz is by referring to the quiz specifically. You can't just pass in a quiz number. You must do: student.q1, student.q2 etc.
Another thing that doesn't make sense is that you are passing the index of student into your setQuiz method. This method already belongs to a student object and there is only one object it can affect, which is itself. You need to choose which student to call the setQuiz method on in whatever location that you're calling it from.
EDIT: Changed the constructor to initialize all grades.
A better way to create your class would be as follows:
public class Student extends TestStudent
{
public String m_name;
public int[] m_grades;
public Student(String cName, int q1, int q2, int q3, int q4, int q5)
{
m_grades = new int[5];
m_grades[0] = q1;
m_grades[1] = q2;
m_grades[2] = q3;
m_grades[3] = q4;
m_grades[4] = q5;
}
public void setQuiz(int grade, int quiz, int student)
{
if (quiz > 0 && quiz <= num_quizzes && grade >= 0 && grade < MAX_GRADE) //Always check yout inputs!!
{
super.studentAr[student].m_grades[quiz-1] = grade;
}
}
}
Then you can use it form outside:
Student josh = new Student("Josh", 10, 20, 30, 40, 50);
josh.setQuiz(51, 1);
josh.setQuiz(60, 2);
josh.setQuiz(20, 3);
Or however you'd like to use it.. Up to you!
Another note. When you call super, in this case you are accessing an array on TestStudent class. I have not seen this class and I do not know if it has a studentAr[] member, but it shouldn't!
This array should be in another class that isn't inherited. It oculd be called StudentList or something like that.
EDIT: In response to your comment. If you need the grades to be accessed exactly as you stated, the only solution that comes to mind is:
public void setQuiz(int grade, int quiz, int student)
{
if (quiz == 1)
super.studentAr[student].q1 = grade;
if (quiz == 2)
super.studentAr[student].q2 = grade;
if (quiz == 3)
super.studentAr[student].q3 = grade;
if (quiz == 4)
super.studentAr[student].q4 = grade;
if (quiz == 5)
super.studentAr[student].q5 = grade;
}
Do note, however, that this is a fairly bad way of doing things. When I was handed assignments like this, I usually tried to do them right, impressed the teacher and walked away with an A+. Of course not all teachers appreciate this, so to stay safe you may want to prepare multiple answers - the specific one and the good one.
If you want to access on of a set of things by an index, you want to use an array, so you can use something like q[quiz].

Function of return statement and method parameters in java?

I'm a beginner in java. I don't know the function of return statement and method parameters in java. Can you please explain it to me further and when should it be used?
Here's my code:
public class Person{
public void display (String name){
System.out.println("hello" + name );
}
public int execute (int num1, int num2){
int result = num1 + num2;
return result;
}
public void display1(int num){
System.out.println("the number is: " + num);
}
}
According to how i understand you question, the return parameter (datatype according to what i understood) is the data type your method should retrun when called (e.g. void int,string,float).
The second question which i think you are asking is when to use the return key name in a method. This should be used when you have a method that you want to return results to the calling variable after execution of the method e.g
//this is a your class that performs some related task
public class Person{
public void display (String name){
System.out.println("hello" + name );
}
public int execute (int num1, int num2){
int result = num1 + num2;
return result;
}
public void display1(int num){
System.out.println("the number is: " + num);
}
}
//main class or the calling class
public class MainCallingClass {
public static void main(String[] args) {
//instantiate the Person class here
Person prsn = new Person();
//calls the execute(),which adds 2 numbers inside Person class
int getSum = prsn.execute(1,1);
System.out.println("Sum of 1 and 1 is: " + getSum );
}
}
Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.
Example:
double sales_tax(double price)
{
return 0.05 * price;
}
After the function has been defined, it can be invoked as follows:
sales_tax(10.00);
In this example, the function has been invoked with the number 10.00. When this happens, 10.00 will be assigned to price, and the function begins calculating its result. The steps for producing the result are specified below enclosed in {} "0.05 * price" indicates that the first thing to do is multiply 0.05 by the value of price, which gives 0.50. "return" means the function will produce the result of "0.05 * price". Therefore, the final result is 0.50.
The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. A brief look at return is presented here.
like for example:
public int execute (int num1, int num2){
int result = num1 + num2;
return result;
}
Person prsn = new Person();
int getSum = prsn.execute(1,1);
the value of getSum will be the value of result through which you have returned in the method execute that you have invoked.
From this page:
This example shows a simple method that computes the area of a rectangle:
public static int computeArea(int width, int height) {
int area; // This is a local variable
area = width * height;
return area;
}
Line 1: This is the method header. The first int indicates that the value this method returns is going to be an integer. The name of the function is "computeArea", and it has two integer parameters: width and height.
Line 2...4: The body of the method starts with the left brace, "{", on the end of the first line. The "{" doesn't have to be on the same line as the header, but this is a common style.
The body of this simple function contains a declaration on line 2, an assignment statement in line 3, and a return statement on line 4. If a method returns a value, then there must be at least one return statement. A void method (one which does not return a value),
does not require a return statement, and will automatically return at the end of the method.

Categories