Can't seem to return value - java

I just edited my post to update my code... I am still getting an error message when I compile stating that "Cannot find symbol". I have never seen this error so I am not sure how to debug it, I really appreciate everyone's help!
public class HealthRecord {
private int ID; // stores ID number
private String last; // stores last name
private String first; //stores first name
private double height; // stores height
private double weight; // stores weight
private double bmi;// i may need to create the bmi variable so that it can be stored (weight / (height*height)) *703;
public HealthRecord( int ID, String last, String first, double height, double weight)
{
this.ID = ID;
this.last = last;
this.first = first;
this.height = height;
this.weight = weight;
this.bmi = bmi;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getFirst() {
return first;
}
public void setFirst(String last) {
this.first = first;
}
public double getheight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getbmi() {
return (weight / (height*height)) *703;
}
public void setbmi(double bmi) {
this.bmi = bmi;
}
}
Next Class
import java.util.Scanner;
import java.io.File;
public class OpenFile
{
private Scanner input;
public void openFile() throws Exception
{
input = new Scanner(new File("medrec.txt")); // opens the text file to be read (weight / (height*height)) *703);
}
public void readFile()
{
int ID; // stores ID number
String last; // stores last name
String first; //stores first name
double height; // stores height
double weight; // stores weight
input.nextLine();
while(input.hasNextLine())
{
ID = input.nextInt();
last = input.next();
first = input.next();
height = input.nextDouble();
weight = input.nextDouble();
HealthRecord healthrecord= new HealthRecord(ID,last,first,height,weight);
System.out.printf("%d", healthrecord.getID(), healthrecord.getBmi());
}
}
public void closeFile()
{
input.close();
}
}

Replace
System.out.printf("%d %d", HealthRecord.getID, HealthRecord.getBmi);
with
System.out.printf("%d %f", healthrecord.getID(), healthrecord.bmi());
Use the healthrecord instance that you created. The method getID requires parenthesis. Also getBmi doesn't exist as a method. Currently you have bmi.
Aside:
Currently this code doesn't compile. All methods in openFile are instance methods. You need to create an instance and use:
Openfile myOpenfile = new Openfile();
myOpenfile.openFile();
myOpenfile.readFile();
myOpenfile.closeFile();
Java naming conventions indicate class names start with uppercase letters, e.g. Openfile
Edit:
In your updated file, getBmi does not exist but rather getbmi:
System.out.printf("%d %f", healthrecord.getID(), healthrecord.getbmi());
^
You may want to rename the method to getBmi to follow method naming conventions.

I don't see any bmi calculation in HealthRecord constructor or in getter method of bmi.
Even I don't see getBmi() method in HealthRecord class.
Add below method in HealthRecord class :
public double getBmi() {
return (weight / (height*height)) *703; //check this formula if it is correct for BMI calculation or not
}
And next you need to use this call in main class:
System.out.printf("%d %d", healthrecord.getID(), healthrecord.getBmi());

Related

How to display all information in toString

I have two classes: Position and Order. In Position class, fields like: name, price. In Order class field: quantity. My problem is how to display: name, price and quantity together in Order class. I thought about delete arraylist and make another one with position and quantity but I doubt it would help me.
package programming.com.pl;
public class Position {
private String name;
private double price = 0;
public Position(String name, double price){
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
public String toString(){
String str = String.format("%4s,%4s", name,price);
return str;
}
}
public class Order {
private int quantity;
final private ArrayList<Position> positions = new ArrayList<Position>();
private int addedPosition;
public Order(int quantity) {
this.quantity = quantity;
}
private double calculateProduct() {
double sum = 0;
for (int i = 0; i < positions.size(); i++) {
sum = positions.get(i).getPrice();
}
return sum;
}
double sumOrder() {
double sum = 0;
for (Position x : positions) {
sum += calculateProduct();
}
return sum;
}
void addPosition(Position p) {
if (!positions.contains(p)) {
positions.add(p);
} else {
quantity++;
}
}
void deletePosition(int index) {
positions.remove(index);
}
public String toString() {
System.out.println("Order is: ");
for (Position p : positions) {
System.out.println(positions.toString());
}
return "Order sum is: " + sumOrder();
}
}
You already are overriding toString method in Position class so you just need to call that toString method on the position object when iterating the position objects from inside your Order class' toString() method.
And as #Federico points out in the comments you shouldn't System.out.println from toString methods. Just append to a string the details you require displaying and return that string.
You can achieve your desired result like so:
public class Position {
.
.
#Override
public String toString() {
return String.format("%4s,%4s\n", name, price);
}
}
public class Order {
.
.
#Override
public String toString() {
StringBuilder sb = new StringBuilder("Order details: \n");
sb.append("Quantity: ").append(quantity).append("\n");
for (Position p : positions) {
sb.append(p);
}
sb.append("Order sum is: ").append(sumOrder());
return sb.toString();
}
}

New to java: I'm not sure how to store the objects in the arrays after it is created. The program gets rid of it, making it null

The main objective was to have a lake and add fish objects to it, which have details about their weight etc. But however, every time a new fish is created, the previous object appears as null instead of its location, which I could use my getName to get the name.
package com. company;
public class Main {
public static void main(String[] args) {
Lake l = new Lake("jersey", 1, 2, 3,4 );
l.addFish("carp", 20, 1);
l.addFish("josh",20,1);
Lake n = new Lake("york",1,2,4,20);
n.addFish("catfish",20,30);
n.addFish("tot",20,30);
n.addFish("salmon",20,30);
n.addFish("shrimp",20,30);
n.addFish("swordfish",20,30);
}
}
package com. company;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Lake {
private String name;
private double length;
private double width;
private double depth;
private final int amountOfFish;
private int currentFishAmount = 0 ;
Lake(String name, double length, double width, double depth, int amountOfFish)
{
this.name = name;
this.length = length;
this.width = width;
this.depth = depth;
this.amountOfFish = amountOfFish;
}
public void addFish (String name, double length, double weight)
{
Fish fishInLake [] = new Fish[amountOfFish];
fishInLake[currentFishAmount]= new Fish(name, length, weight);
System.out.println("Lake: " + this.name + "|" + "Fish:" + ""+ fishInLake[currentFishAmount].getName() + fishInLake[currentFishAmount].getLength());
System.out.println(currentFishAmount);
currentFishAmount++;
System.out.println(Arrays.toString(fishInLake));
}
}
package com.company;
import java.lang.reflect.Array;
public class Fish {
private String name;
private double length;
private double weight;
Fish (String name, double length, double weight){
this.name = name;
this.length = length;
this.weight = weight;
}
public String getName(){
return this.name;
}
public double getLength(){
return this.length;
}
public double getWeight(){
return this.weight;
}
}
The main objective was to have a lake and add fish objects to it, which have details about their weight etc. But however, every time a new fish is created, the previous object appears as null instead of its location, which I could use my getName to get the name.
First off, to make your output a bit more readable, add a toString() method in your Fish class:
public String toString(){
return this.name;
}
Next, since you want the array to be saved every time a new fish is added to the lake, we want to make the array a private instance variable, and then initialize it in our constructor:
package com. company;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Lake {
private String name;
private double length;
private double width;
private double depth;
private final int amountOfFish;
private int currentFishAmount = 0 ;
private Fish[] fishInLake;
Lake(String name, double length, double width, double depth, int amountOfFish)
{
this.name = name;
this.length = length;
this.width = width;
this.depth = depth;
this.amountOfFish = amountOfFish;
this.fishInLake = new Fish[amountOfFish];
}
public void addFish (String name, double length, double weight)
{
fishInLake[currentFishAmount]= new Fish(name, length, weight);
System.out.println("Lake: " + this.name + "|" + "Fish:" + ""+ fishInLake[currentFishAmount].getName() + fishInLake[currentFishAmount].getLength());
System.out.println(currentFishAmount);
currentFishAmount++;
System.out.println(Arrays.toString(fishInLake));
}
}
better to create a static method or a static Array, otherwise every time that tries to insert data, the previous data will be disappearing, with a static Array the whole data will be there until program execution finish.

Java: how to pass a variable from one class to another using access modifiers

So I'm brand new to java, and have experience doing this in C# but something seems different. I am trying to make the input from the user be passed to the set method for the variable in another class.
//this is the class im trying to pass the variable to
public class HealthProfile
{
private String name="";
private double age;
private double weight;
private double height;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
// this is the method im trying to pass the value from taking the users input
import java.util.Scanner;
public class Lab1Main {
public void getInput()
{
HealthProfile user = new HealthProfile();
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name: ");
user.setName(input.nextLine());
System.out.print("Your Age: ");
user.setAge(input.nextDouble());
System.out.print("Your Weight: ");
user.setWeight(Double.parseDouble(input.nextLine()));
}
}
Wrong syntax:
user.setName(aName)= input.nextLine();
should be
user.setName(input.nextLine());
for example. In Java, there is no such thing as a "named parameter"; when you call methods, you simply have to provide the parameters simply "in place", in the exact same order as specified in the method declaration.
And a word on the title of your question: access modifiers do only control which fields/methods can be accesses from other classes; you cannot "use" them to pass anything.

ArrayList "get(i)" command using a public class variable

I am trying to get the length of the longest first name and saving it as int longest, but my code is not properly fetching the first names from my class Student
here is my code:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (int i = 0; i < studentList.size(); i++)
{
if (studentList.get(i).getFirstName.length() > longest);
{
longest = studentList.get(i).getFirstName.length();
}
}
return longest;
}
Here is where I am fetching my variables:
public class Student
{
private int IDnum;
private String firstName;
private String lastName;
private int gradYear;
private double gradePoint;
public Student(int ID, String first, String last, int year, double GPA)
{
IDnum = ID;
firstName = first;
lastName = last;
gradYear = year;
gradePoint = GPA;
}
public int getID()
{
return IDnum;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getYear()
{
return gradYear;
}
public double getGPA()
{
return gradePoint;
}
}
getFirstName is not a variable, it's a method. Java syntax requires parentheses when calling a method (even if the method takes no arguments):
if (studentList.get(i).getFirstName().length() > longest);
^^
(and on the next line).
By the way, you can replace the entire if construct with:
longest = Math.max(studentList.get(i).getFirstName().length(), longest);
To simplify this further, you could use a for-each loop:
public static int findLongestFirstName(ArrayList<Student> studentList)
{
int longest = 0;
for (Student student : studentList) {
longest = Math.max(student.getFirstName().length(), longest);
}
return longest;
}
Your code seems fine however there is a semi colon at the end of your if statement which is causing the issue.

My getStats method pops up with infinity numbers

In Java, my basketball players keep sending back "infinity" in my getStats method and I do not know why. Can someone help please? I needed getters and setters so I have that. I am suppose to test the getStats() methods but it errors out every time. At first it was NaNa now its infinity
public class BasketBallPlayer
{
// instance variables - replace the example below with your own
private String name;
private int height;
private int weight;
private double freeThrowsAttempted;
private double freeThrowsMade;
private double twoPointFieldGoalsAttempted;
private double twoPointFieldGoalsMade;
private double threePointersAttempted;
private double threePointersMade;
private int turnovers;
private int assist;
private String stats;
public BasketBallPlayer(String name, int height, int weight, double freeThrowsMade, double twoPointFieldGoalsAttempted,double twoPointFieldGoalsMade, double threePointersAttempted, double threePointersMade, int assist, int turnovers)
{
//identifies the age, name, height-in., weight-lbs
this.name=name;
this.height=height;
this.weight=weight;
this.freeThrowsAttempted=freeThrowsAttempted;
this.freeThrowsMade=freeThrowsMade;
this.twoPointFieldGoalsAttempted=twoPointFieldGoalsAttempted;
this.threePointersMade=threePointersMade;
this.turnovers=turnovers;
this.assist=assist;
}
public BasketBallPlayer(int weight, int height, String name)
//identifies the weight(lbs.), height(inches) and String name
{
//identifies the name, height-in., weight-lbs
this.name=name;
this.height=height;
this.weight=weight;
}
//Sets the Name
public void setName(String name)
{
this.name=name;
}
//Sets the Height
public void setHeight (int height)
{
this.height=height;
}
//Sets the Weight
public void setWeight (int weight)
{
this.weight=weight;
}
//Sets the Free Throws Attempted
public void setFreeThrowsAttempted( double freeThrowsAttempted)
{
this.freeThrowsAttempted=freeThrowsAttempted;
}
//Sets the Free Throws Made
public void setFreeThrowsMade(double freeThrowsMade)
{
this.freeThrowsMade=freeThrowsMade;
}
// Sets two Point Field Goals Attempted
public void setTwoPointFieldGoalsAttempted (double twoPointFieldGoalsAttempted)
{
this.twoPointFieldGoalsAttempted=twoPointFieldGoalsAttempted;
}
public void setTwoPointFieldGoalsMade (double twoPointFieldGoalsMade)
{
this.twoPointFieldGoalsMade=twoPointFieldGoalsMade;
}
public void setThreePointerAttempted(double threePointersAttempted)
{
this.threePointersAttempted=threePointersAttempted;
}
public void setThreePointersMade(double threePointersMade)
{
this.threePointersMade=threePointersMade;
}
public void setTurnovers(int turnovers)
{
this.turnovers=turnovers;
}
public void setAssist(int assist)
{
this.assist=assist;
}
//Returns a Name
public String getName()
{
return name;
}
public int getHeight ()
{
return height;
}
public int getWeight ()
{
return weight;
}
public double getFreeThrowsAttempted()
{
return freeThrowsAttempted;
}
public double getfreeThrowsMade()
{
return freeThrowsMade;
}
public double getTwoPointFieldGoalsAttempted ()
{
return twoPointFieldGoalsAttempted;
}
public double getTwoPointFieldGoalsMade ()
{
return twoPointFieldGoalsMade;
}
public double getThreePointerAttempted()
{
return threePointersAttempted;
}
public double getthreePointersMade()
{
return threePointersMade;
}
public int getTurnovers()
{
return turnovers;
}
public int gettAssist()
{
return assist;
}
/** The geStats Method allows you to get all information on the player in print. All Percentages
*
*/
public void getStats()
{
double Percentage1;
double Percentage2;
double Percentage3;
Percentage1=(double)((twoPointFieldGoalsMade*100)/twoPointFieldGoalsAttempted);
Percentage2=((double)(threePointersMade*100)/threePointersAttempted);
Percentage3=((double)((freeThrowsMade*100)/freeThrowsAttempted));
System.out.println("*************************");
System.out.println("BasketBall Player Name:" + name);
System.out.println("Field Goal Percentage:" + Percentage1 +"%");
System.out.println("3 Pointer Percentage:" + Percentage2 +"%");
System.out.println("Free Throw Percentage:" + Percentage3 +"%");
System.out.println("Assist to Turnover Ration:" + assist/turnovers);
System.out.println("*************************");
}
}
First, you should not be using doubles for these number. It just accounts to inefficiency and makes no sense. However, when using ints, you have to note that you cannot directly get a percentage when dividing two ints. This piece of code should work, you may want to include some code that checks that the divisors are not 0.
private int freeThrowsAttempted;
private int freeThrowsMade;
private int twoPointFieldGoalsAttempted;
private int twoPointFieldGoalsMade;
private int threePointersAttempted;
private int threePointersMade;
...
double percentage1 = (twoPointFieldGoalsMade * 100F) / twoPointFieldGoalsAttempted;
double percentage2 = (threePointersMade * 100F) / threePointersAttempted;
double percentage3 = (freeThrowsMade * 100F) / freeThrowsAttempted;

Categories