Java Code Questions - java

I want to implement a class which includes a student's name, their GPA, grade level, and their final score. We had to create a Tester along with the initial class creates 2 different students, prints their grade level, GPA, their name, and the calculated final test score.
Formula to calculate final test score = .60 * written + .40 * handsOn
Any help would be appreciated, I can't get this program down and I've been trying for quite a while now.
Here is my code:
Tester:
public class IntroToJavaTester
{
public static void main()
{
IntroToJava j1 = new IntroToJava("Joe", 11, 3.2);
System.out.println(j1.getName());
System.out.println(j1.getGradeLevel());
System.out.println(j1.getGPA());
System.out.println(j1.getFinalScore(written, handsOn));
IntroToJava j2 = new IntroToJava("Jim", 11, 3.2);
System.out.println(j2.getName());
System.out.println(j2.getGradeLevel());
System.out.println(j2.getGPA());
System.out.println(j2.getFinalScore( written,handsOn));
}
}
Here is the IntroToJava class:
public class IntroToJava
{
private String name;
private int glev;
private double gpa;
private double finalscore;
private double written = 80;
private double handsOn = 90;
public IntroToJava(String a, int b, double c, double d, double e)
{
name = a;
glev = b;
gpa = c;
written = d;
handsOn = e;
}
public String getName()
{
return name;
}
public int getGradeLevel()
{
return glev;
}
public double getGPA ()
{
return gpa;
}
public double getFinalScore(int written, int handsOn)
{
finalscore = .60*written+.40*handsOn;
return finalscore;
}
}

Your IntroToJava constructor is defined with 5 arguments and you're calling it with only 3 in IntroToJavaTester.
The two arguments you're omitting appear to correspond to the fields written and handsOn.
You've defined getFinalScore to take two arguments with the same names but a different type.
I suspect what you probably really want is for getFinalScore to take no arguments but use these two fields.
Or perhaps getFinalScore is supposed to just be a getter for the field finalScore which doesn't seem to be set or used anywhere, but has a suspiciously similar name.

Related

Having trouble with passing user defined parameters inside my object

I'm being asked to pass more arguments to match my constructor but I have no idea what to pass into them.
I have multiple instance variables but only a few of them will be defined by the user (the vertices) and the others are going to defined with their respective methods. If I take everything except my vertices outside of my constructor to solve the error I am left with my final output being left as 0 for most of my reports.
Is my constructor the problem or the parameters in my object at fault?
import java.lang.Math;
public class Triangle {
//instance variables
private double VertAx, VertAy, VertBx, VertBy, VertCx, VertCy;
private double lengthAB, lengthBC, lengthCA;
private double Perimeter, Area;
private double H = Perimeter/2;
//Triangle Constructor
public Triangle(double userVertAx, double userVertAy, double userVertBx, double userVertBy, double userVertCx, double userVertCy, double userlengthAB, double userlengthBC, double userlengthCA, double userPerimeter, double userArea, double userH) {
userVertAx = this.VertAx;
userVertAy = this.VertAy;
userVertBx = this.VertBx;
userVertBy = this.VertBy;
userVertCx = this.VertCx;
userVertCy = this.VertCy;
userlengthAB = this.lengthAB;
userlengthBC = this.lengthBC;
userlengthCA = this.lengthCA;
userPerimeter = this.Perimeter;
userArea = this.Area;
userH = this.H;
}
public double lengthAB(double userVertAx, double userVertAy, double userVertBx, double userVertBy) {
return lengthAB = Math.sqrt( (Math.pow((userVertBx - userVertAx), 2)) + (Math.pow((userVertBy - userVertAy), 2)));
}
public double lengthBC(double userVertBx, double userVertBy, double userVertCx, double userVertCy) {
return lengthBC = Math.sqrt( (Math.pow((userVertCx - userVertBx), 2)) + (Math.pow((userVertCy - userVertBy), 2)));
}
public double lengthCA(double userVertCx, double userVertCy, double userVertAx, double userVertAy) {
return lengthCA = Math.sqrt( (Math.pow((userVertAx - userVertCx), 2)) + (Math.pow((userVertAy - userVertCy), 2)));
}
public void setPerimeter(double userlengthAB, double userlengthBC, double userlengthCA) {
Perimeter = userlengthAB + userlengthBC + userlengthCA;
}
public double getPerimeter() {
return Perimeter;
}
public void setArea(double userlengthAB, double userlengthBC, double userlengthCA, double userH) {
Area = Math.sqrt(userH*(userH-userlengthAB)*(userH-userlengthBC)*(userH-userlengthCA));
}
public double getArea() {
double Area = getArea();
return Area;
}
public String toString() {
return String.format("Vertices: A(%f, %f) B(%f, %f) C(%f, %f)\nSide Lengths: AB=%f BC=%f CA=%f\nPerimeter: %f\nArea: %f", VertAx, VertAy, VertBx, VertBy, VertCx, VertCy, lengthAB, lengthBC, lengthCA, Perimeter, Area);
}
}
public class TriangleTest {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner Vertices = new Scanner(System.in);
System.out.println("Welcome to the Triangle Test enter each coordinate of your three vertices SEPERATELY");
System.out.println("Enter Vertex A X");
Double VAX = Vertices.nextDouble();
System.out.println("Enter Vertex A Y");
Double VAY = Vertices.nextDouble();
System.out.println("Enter Vertex B X");
Double VBX = Vertices.nextDouble();
System.out.println("Enter Vertex B Y");
Double VBY = Vertices.nextDouble();
System.out.println("Enter Vertex C X");
Double VCX = Vertices.nextDouble();
System.out.println("Enter Vertex C Y");
Double VCY = Vertices.nextDouble();
//ERROR
Triangle UserTriangle = new Triangle(VAX, VAY, VBX, VBY, VCX, VCY);
//ERROR ^
UserTriangle.lengthAB(VAX, VAY, VBX, VBY);
UserTriangle.lengthBC(VBX, VBY, VCX, VCY);
UserTriangle.lengthCA(VCX, VCY, VAX, VAY);
UserTriangle.getPerimeter();
UserTriangle.getArea();
System.out.println(UserTriangle.toString());
}
}
I am expecting some way to pass the right parameters into my UserTriangle but I am confused as to how. Thank you for any help anyone can provide. My understanding with classes and objects were good with implementing user input but this one seems so tricky to me considering some of the variables are defined in methods and some are defined by the user.
Constructor called with a mismatched number of arguments
You defined your constructor as accepting 12 arguments, but then you called it with only 6 arguments. This is the error you're referring to. To solve this you have 3 options
Provide all the 12 arguments the constructor needs
Define your constructor as receiving 6 arguments
Refactor (see below for instructions), which is the way to go in my opinion
Reverse the initialization statements in your constructor
To initialize your attributes write this.VertAx = userVertAx instead of userVertAx = this.VertAx; (reverse the statement basically)
This goes for all the other attributes too (userlengthAB, userPerimeter, etc...)
Note
It's better to use the Java naming conventions so you can make the difference say between attributes and classes. Attributes and variables should start with a lowercase and classes with an uppercase.
Edit: Refactoring suggestion
An even better writing is to use less arguments in your constructor. Having too many arguments is considered a code smell and will make your code less readable/maintainable, etc...
To handle that you can encapsulate some concepts in classes. For example you can have
public class Vertex {
private double x;
private double y;
public Vertex(double x, double y) {
this.x = x;
this.y = y;
}
public class TriangleVertices {
private vertexA;
private vertexB;
private vertexC;
public TriangleVertices (Vertex a, Vertex b, Vertex c) {
vertexA = a;
vertexB = b;
vertexC = c;
}
}
public class Triangle {
private TriangleVertices vertices;
// other attributes
// You have now 5 arguments less!
public Triangle(TriangleVertices vertices, // other attributes) {
this.vertices = vertices;
// Initialize other attributes
}
}
Here "this" is a keyword which points the constructor to the variables that are declared in the created class (in your case created class is Triangle). we use "this" keyword when
the variable of parameter has the same name as the variable declared in the created class.For example;
class A {
int NewVar;
A (double NewVar){
this.NewVar = NewVar; //here this.NewVar is pointing to NewVar of type int
}
}
Change this in your code. This might solve your problem.
public Triangle(double userVertAx, double userVertAy, double userVertBx, double userVertBy, double userVertCx, double userVertCy, double userlengthAB, double userlengthBC, double userlengthCA, double userPerimeter, double userArea, double userH) {
this.VertAx = userVertAx;
this.VertAy = userVertAy;
this.VertBx = userVertBx;
this.VertBy = userVertBy;
this.VertCx = userVertCx;
this.VertCy = userVertCy;
this.lengthAB = userlengthAB;
this.lengthBC = userlengthBC;
this.lengthCA = userlengthCA ;
this.Perimeter = userPerimeter ;
this.Area = userArea;
this.H = userH ;
}

How to create a addline method?

I am having issues with my assignment about adding a new line using the below lines 1 through 4, as instances of InvoiceLine class into my Invoice class.
Instance Variables:
Line1: a variable of type InvoiceLine class
Line2: a variable of type InvoiceLine class.
Line3: a variable of type InvoiceLine class.
Line4: a variable of type InvoiceLine class.
addLine is a method that takes the following four input parameters: item number, item description, item price, and quantity.
The method then adds a line to the invoice only if the invoice has less than four lines. If the invoice already has four lines, then this method should print an error message.
How would I do it to make it work properly? I would appreciate any help.
Invoice Class:
public class Invoice {
// Instance Variables
private String customerName;
private int numItems;
private InvoiceLine line1;
private InvoiceLine line2;
private InvoiceLine line3;
private InvoiceLine line4;
// Contructors
public Invoice(){}
public Invoice(String customerNam){
customerName = customerNam;
}
//Getters
public String getCustomerName(){
return customerName;
}
//Setters
private void setCustomerName(String customerNam){
customerName = customerNam;
}
public void addLine(int itemNum, String Description, double itemPrice, int quantity){
if (numItems <= 4) {
numItems += line1;
if (numItems <= 4)
numItems += line2;
if (numItems <= 4)
numItems += line3;
if (numItems <= 4)
numItems += line4;
}
if (numItems == 4){
System.out.print("Error");
}
}
public double getInvoiceTotal(){
numItems *= numItems;
return numItems;
}
public String toString(){
String invoiceOutput = "";
invoiceOutput += (customerName + " brought "+ numItems);
return invoiceOutput;
}
}
InvoiceLine Class:
public class InvoiceLine {
//Instance Variables
private Item itemSold;
private int quantity;
public double total = 0;
// Constructors
public InvoiceLine(){}
public InvoiceLine(Item itemSold, int quantity){
this.itemSold = itemSold;
this.quantity = quantity;
}
public InvoiceLine(int itemNum, String itemDescription, double itemPrice, int quantity){
this.itemSold = new Item(itemNum, itemDescription, itemPrice);
this.quantity = quantity;
}
//Getters
public Item getItemSold() {
return itemSold;
}
public int getQuantity(){
return quantity;
}
//Setters
private void setItemSold(Item itemSold){
this.itemSold = itemSold;
}
private void setQuantity(int quantity){
this.quantity = quantity;
}
// Methods
public double getLineTotal(double total){
total = (quantity * itemSold.getItemPrice());
return total;
}
public String toString(){
String invoiceLine = "";
invoiceLine = (itemSold + " brought "+ quantity + ", which the total cost is "+ total);
return invoiceLine;
}
}
Looks like you will want to go back through your addLine method. Based on the description you provided for this method (which I assume is from your assignment), it sounds like this method should just set one of your InvoiceLine instance variables for that Invoice. I don't want to just write the solution for you as this is for an assignment so the point is to learn from doing! But here are some tips for where to focus:
Pay attention to the instance variable types in your Invoice class. You are trying to "add" these to your numItems variable, which has type int. This wont work well!
You shouldn't need to worry about checking the numItems value more than once in the addLines method. Once you check it and see it is less than 4, you know you should have available lines to add!
If you are adding lines, you need to be creating some new InvoiceLines. Take a look at one of your constructors for that class. You should see one of those would work well for the parameters you are given in the addLine method.
One important thing I'll point out though that should help you avoid more tedious hiccups: you are going to want to initialize your numItems variable to 0! You can either do this in the constructors or just set its default value in its declaration, like so: private int numItems = 0;.
Then, remember you have to increment/decrement this variable in your methods whenever a line is added or removed, it's not automatic. So the last thing you will want to do in your addLine method is numItems++. But only if everything was added successfully! (In otherwords, if the method wasn't actually able to add a line because there were already 4, you don't want to increment the numItems).
Hope that helps point you in the right direction! I'd give it another shot and see how far you get. If you run into other specific issues you can't figure out, feel free to comment.

Need assistance printing out a number from another method

I am working on a small RPG project and I can't print a number from another method.
Here's the main:
///////// SMTMain /////////
//Note: this is a parody game and not to be meant for actual retail purposes.
// SMTMain.java
import java.util.Scanner;
public class SMTMain
{
public static void main( String[] args )
{
Scanner scan = new Scanner(System.in);
SMTBattle battle = new SMTBattle();//runs the battle method, works fine.
SMTStats stats = new SMTStats();
//battle.battle(); commented out battle until i can get stats working
System.out.print(stats.pcstats(str));
//error, cannot find symbol ^
} // end main
} // end class SMTMain
And the file containing all the stats:
///////// SMTStats /////////
// SMTStats.java
import java.util.Scanner;
public class SMTStats
{
Scanner input = new Scanner( System.in );
////////Main Stats///////////////
private int lvl; //level
private double str; //strength
private double agi; //agility
private double itl; //intellect
private double wis; //wisdom
private double lk; //luck
//////Main Stats end/////////////
///////stats that are influenced by main stats or gear/////////
private double hp; // health
private double mp; //mana
private double arm; //armor
private double atk; //attack
private double crit; //critical
private double hit; //chance to hit
private double def; //defense
private double dge; //dodge
////////stats etc. ends//////////////////////////////////
double pcstats; //player character function
public double pcstats() //player character stats
{
//int lvl = 1; //worried about just str currently
double str = 10.0;
/*agi = 10;
itl = 10;
wis = 10;
lk = 10;
hp = 30;
mp = 30;
arm = 30;
atk = 1.2 * str;
crit = (1.5 * lk) / 2;
hit = 1.5 * (agi * 2);
def = arm / str;
dge = (agi * 1);*/
return pcstats;
}
} // end class SMTStats
I tried googling my error but I couldn't find an answer to my question and I'm still fairly new to java programming, I was hoping y'all would lead me into the right direction.
What Java tries to do:
Java tries to find some Variable called str. But SMTMain has no variable called str. The class SMTMain can't "see" what you have declared in another class (SMTStats).
What you are probably trying to do:
The variable stats is an object (so called instance of the class) of the class SMTStats.
You need one more method (function of an Object) in the class SMTStats.
Usually, you make so called getter and setter methods.
Code:
The getter for str in SMTStats:
public int getStr() {
return str;
}
The method getStr() returns the variable str to SMTMain.
The setter for str in SMTStats:
public void setStr(double newStr) {
str = newStr;
}
The method setStr sets the variable from SMTMain.
In the class SMTMain you can now print the variable str from SMTStats:
System.out.print(stats.getStr());
The name of the getter method implies what variable you want to get/return.
A nice java tutorial by the way (Chapter 25 is Object Oriented Programming):
http://chortle.ccsu.edu/java5/index.html

<Identifier> Expected- Having major difficulty, New to coding

class Maths{
// Attributes of maths
private int num1;
private int num2;
//Constructor
public Maths ***- This is where the error is***
{
add = a;
subtract = s;
multiply = m;
divide = d;
}
//Get me some Accessors
public String getAdd()
{
return add;
}
public string getSubtract()
{
return subtract;
}
public String getMultiply()
{
return multiply;
}
public String getDivide()
{
return divide;
}
}
}
Alright so I'm new to programming, Absolutely newborn. I'm really not sure what to do for this. I need to "Write a class called Maths. It has 2 attributes called num1 and num2. It has a constructor. It will have methods called Add(), subtract(), multiply() and divide().(Hint: integer division use modulus operator). Most of these methods return the result.
Write all the getters and setters and a toString() method."
In Maths constructor you have forgotten parenthesis ()
Do like this
public Maths()
{
add = a;
subtract = s;
multiply = m;
divide = d;
}
constructor has the same name as class and parenthesis.
this is what you need to put there.
public Maths()
{
add = a;
subtract = s;
multiply = m;
divide = d;
}

Completing a class definition

Suppose that you are given the following PetDriver class, which includes a main method:
public class PetDriver{
public static void main(String[] args){
int weight = 40;
Pet doggie = new Pet("Rover", weight);
System.out.println("my pet's name is " + doggie.getName());
System.out.println("my pet's weight is " + doggie.getWeight());
}
}
Executing main produces the following output:
my pet's name is Rover
my pet's weight is 40
My code is as follows but It is returning null.
public class pet {
public String name;
public int weight = 40;
public Pet (String y, int x){
y = name;
x = weight;
}
public String getName(){
return name;
}
public int getWeight(){
return weight;
}
}
Thanks!
In your constructor, you should do it the other way around:
public Pet (String y, int x){
name = y; // instead of y = name
weight = x; // instead of x = weight
}
What you did was assigning the member value to the parameters of the constructor, instead of the other way around. Therefore the member value nameitself was never written, and therefore it was null.
Your constructor does not assign the value to the properties. Change them to the following.
public Pet (String y, int x){
name = y;
weight = x;
}

Categories