How to get the output of Calories - while-loop

When running this program we are able to get the BMR output but it won't plug into the equation to give us calorie output. It seems to me like it's completely ignoring the activity part of the code. We had a user input 1 2 or 3 in a different part of the code. Any help will be appreciated.
public class Calculate
{
static UserInput dataInput = new UserInput();
static double BMR;
static double calorie;
public void calculateReturn()
{
output();
}
private void output()
{
System.out.println("Your daily caloric needs are: " + calorie);
calculate();
}
private void calculate()
{
UserInput dataInput = new UserInput();
if (dataInput.getGender() == 1)
{
maleBMR();
}
else
{
femaleBMR();
}
activity();
}
private void maleBMR()
{
double BMR = (66 + (6.23 * dataInput.getWeight()) + (12.7 * dataInput.getHeight()) - (6.8 * dataInput.getAge()));
System.out.println("BMR: " + BMR);
}
private void femaleBMR()
{
double BMR = (665 + (4.35 * dataInput.getWeight()) + (4.7 * dataInput.getHeight()) - (4.7 * dataInput.getAge()));
System.out.println("BMR: " + BMR);
}
private void activity()
{
double calorie;
if (dataInput.getActivity() == 1)
{
calorie = (BMR * 1.2);
}
else if (dataInput.getActivity() == 2)
{
calorie = (BMR * 1.5);
}
else
{
calorie = (BMR * 1.9);
}
}
}

You are defining two calorie variables: one of them is a global variable defined within the Calculate class and the other is defined inside the activity() function. That second calorie variable is only visible in your activity function. So activity function will only change the value of your local calorie variable not the global one.

Related

Java toString() method override

With the two classes I am making square objects in preparation for my exam tomorrow. S1 is created using default and S2 via non-default. For some reason the it will print out all values excluding the Side as 0. Please help.
public class SquareRunner{
public static void main(String[] args)
{
Square S1 = new Square();
Square S2 = new Square(4);
System.out.println(S1.toString());
System.out.println(S2.toString());
}
}
import java.lang.Math;
public class Square
{
private int s, a, p;
private double d;
public Square()
{
s = 1;
}
public Square(int side)
{
s = side;
}
public int getSide()
{
return s;
}
public int getArea()
{
a = s * s;
return a;
}
public double getDiagonal()
{
double d;
d = Math.sqrt(Math.pow(s,2) + Math.pow(s,2));
return d;
}
public int getPerimeter()
{
p = 4 * s;
return p;
}
public String toString()
{
return "Side: " + s + " Perimeter: " + p + " Area: " + a + " Diagonal: "
+ d;
}
}
Try this out
public String toString()
{
return "Side: " + s + " Perimeter: " + this.getPerimeter() + " Area: " + this.getArea() + " Diagonal: "
+ this.getDiagonal();
}
If you want to print out the perimeter, area, and diagonal then you have to calculate those values to be printed.
If you want to print these out in your SquareRunner class then you can do this
public class SquareRunner{
public static void main(String[] args)
{
Square S1 = new Square();
Square S2 = new Square(4);
System.out.println(S1.getArea());
...
...
}
}

Adding message to faceContext is not working in Java EE7 run on glassFish?

I am doing the tutorial on Java EE7 that comes with glassFish installation. It is also available here. The code is present in glassFish server installation directory
/glassFish_installation/glassfish4/docs/javaee-tutorial/examples/cdi/guessnumber-cdi.
The code works fine as it is. It currently displays correct! when a user correctly guesses the number but does not display failed at end of the game. so I introduced, just one minor change to display the failed message. I have added comments right above the relevant change in code.
Somehow, this change did not help. That is, the at the end of the game, failed message is not displayed.
But the game works as usual. I would like to know why this did not work and how to correct it?
Thanks
public class UserNumberBean implements Serializable {
private static final long serialVersionUID = -7698506329160109476L;
private int number;
private Integer userNumber;
private int minimum;
private int remainingGuesses;
#Inject
#MaxNumber
private int maxNumber;
private int maximum;
#Inject
#Random
Instance<Integer> randomInt;
public UserNumberBean() {
}
public int getNumber() {
return number;
}
public void setUserNumber(Integer user_number) {
userNumber = user_number;
}
public Integer getUserNumber() {
return userNumber;
}
public int getMaximum() {
return (this.maximum);
}
public void setMaximum(int maximum) {
this.maximum = maximum;
}
public int getMinimum() {
return (this.minimum);
}
public void setMinimum(int minimum) {
this.minimum = minimum;
}
public int getRemainingGuesses() {
return remainingGuesses;
}
public String check() throws InterruptedException {
if (userNumber > number) {
maximum = userNumber - 1;
}
if (userNumber < number) {
minimum = userNumber + 1;
}
if (userNumber == number) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("Correct!"));
}
//if remainingGuesses is less than or equal to zero, display failed message
//-----------------------------------------------
if (remainingGuesses-- <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
return null;
}
#PostConstruct
public void reset() {
this.minimum = 0;
this.userNumber = 0;
this.remainingGuesses = 10;
this.maximum = maxNumber;
this.number = randomInt.get();
}
public void validateNumberRange(FacesContext context,
UIComponent toValidate,
Object value) {
int input = (Integer) value;
if (input < minimum || input > maximum) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("Invalid guess");
context.addMessage(toValidate.getClientId(context), message);
}
}
}
Adding the FacesMessage is actually working, the problem is that you are using postdecrement in your condition.
Postdecrement, as the name suggests, is decremented AFTER the execution of the statement containing the postdecrement.
That means, if you write:
if (remainingGuesses-- <= 0) {
the var remainingGuesses is decremented after the if-condition was evaluated.
In your case, when the last guess is checked, remainingGuesses is actually 1 and therefore the if-condition is not true and the message is not added.
Different obvious solutions:
if (remainingGuesses-- <= 1) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
or
if (--remainingGuesses <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
or
remainingGuesses--;
if (remainingGuesses <= 0) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage("failed "));
}
See also:
Is there a difference between x++ and ++x in java?
Difference between i++ and ++i in a loop?

How do you input data into a constructor from scanner?

I am trying to take a constructor(string, string, double) and set the value in it with a scanner input. any help is appreciated. The code is list below.
My programs can assign the values that i put in, but I want to be able to assign them from the keyboard and I would like to use only one constructor method to accomplish this. Thanks
I have it broken up into two classes:
import java.util.Scanner;
public class EmployeeTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
Employee employee1 = new Employee("james", "ry", 3200);
Employee employee2 = new Employee("jim" , "bob" , 2500.56 );
System.out.println("What is employyee 1's first name? ");
employee1.setFname(input.nextLine());
}
}
class Employee
{
private String fname;
private String lname;
private double pay;
public Employee(String fname, String lname, double pay)
{
this.setFname(fname);
this.lname = lname;
this.pay = pay;
System.out.println("Employee " + fname +" "+ lname + " makes $" +
+ pay + " this month and with a 10% raise, their new pay is $" + (pay * .10 + pay));
}
void setfname(String fn)
{
setFname(fn);
}
void setlname(String ln)
{
lname = ln;
}
void setpay (double sal)
{
pay = sal;
}
String getfname()
{
return getFname();
}
String getlname()
{
return lname;
}
double getpay()
{
if (pay < 0.00)
{
return pay = 0.0;
}
return pay;
}
public String getFname() {
return fname;
}
public void setFname(String fname)
{
this.fname = fname;
}
}
You can modify you EmployeeTest class something like
class EmployeeTest {
public static void main (String...arg) {
Scanner s = new Scanner(System.in);
String[] elements = null;
while (s.hasNextLine()) {
elements = s.nextLine().split("\\s+");
//To make sure that we have all the three values
//using which we want to construct the object
if (elements.length == 3) {
//call to the method which creates the object needed
//createObject(elements[0], elements[1], Double.parseDouble(elements[2]))
//or, directly use these values to instantiate Employee object
} else {
System.out.println("Wrong values passed");
break;
}
}
s.close();
}
}

Defining methods and variables

I am a beginner and I am trying to understand what is static, private, public. Please see the following example written by me. It works, but I have very big doubts whether this is a correct way of defining variables and methods. Thanks in advance!
import java.util.Scanner;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Biorhytm {
private static String nameOne;
private static String nameTwo;
private static String dobOneIn;
private static String dobTwoIn;
private static Date dobOne;
private static Date dobTwo;
static int diff;
public static Date getDobOne() {
return dobOne;
}
public static void setDobOne(Date dobOne) {
Biorhytm.dobOne = dobOne;
}
public static Date getDobTwo() {
return dobTwo;
}
public static void setDobTwo(Date dobTwo) {
Biorhytm.dobTwo = dobTwo;
}
public static String getDobOneIn() {
return dobOneIn;
}
public static void setDobOneIn(String dobOneIn) {
Biorhytm.dobOneIn = dobOneIn;
}
public static String getDobTwoIn() {
return dobTwoIn;
}
public static void setDobTwoIn(String dobTwoIn) {
Biorhytm.dobTwoIn = dobTwoIn;
}
public static String getNameOne() {
return nameOne;
}
public static void setNameOne(String nameOne) {
Biorhytm.nameOne = nameOne;
}
public static String getNameTwo() {
return nameTwo;
}
public static void setNameTwo(String nameTwo) {
Biorhytm.nameTwo = nameTwo;
}
public static int diffCalc() {
return diff = Math.abs((int)((getDobOne().getTime() - getDobTwo().getTime()) / (24 * 60 * 60 * 1000)));
}
public static void main(String[] args) {
float physicalBio;
float emotionalBio;
float intellectualBio;
boolean validEntry;
Scanner input = new Scanner(System.in);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("EEEE, MMMM d, yyyy", java.util.Locale.US);
System.out.println("Enter name of first person!");
setNameOne(input.nextLine());
if (getNameOne().equals("")) {
setNameOne("first person");
}
System.out.println("Enter name of second person!");
setNameTwo(input.nextLine());
if (getNameTwo().equals("")) {
setNameTwo("second person");
}
do {
try {
System.out.println("Enter date of birth of " + getNameOne() + "! (MM/DD/YYYY)");
setDobOneIn(input.nextLine());
setDobOne(format.parse(getDobOneIn()));
validEntry = true;
}
catch (ParseException e) {
validEntry = false;
}
} while (!validEntry);
do {
try {
System.out.println("Enter date of birth of " + getNameTwo() + "! (MM/DD/YYYY)");
setDobTwoIn(input.nextLine());
setDobTwo(format.parse(getDobTwoIn()));
validEntry = true;
}
catch (ParseException e) {
validEntry = false;
}
} while (!validEntry);
System.out.println();
System.out.println("DOB of " + getNameOne() + ": " + format2.format(getDobOne()) + ".");
System.out.println("DOB of " + getNameTwo() + ": " + format2.format(getDobTwo()) + ".");
System.out.println("Difference between DOBs (days): " + diffCalc() + ".");
physicalBio = diffCalc() % 23;
emotionalBio = diffCalc() % 28;
intellectualBio = diffCalc() % 33;
physicalBio /= 23;
emotionalBio /= 28;
intellectualBio /= 33;
if (physicalBio > 0.5) {
physicalBio = 1 - physicalBio;
}
if (emotionalBio > 0.5) {
emotionalBio = 1 - emotionalBio;
}
if (intellectualBio > 0.5) {
intellectualBio = 1 - intellectualBio;
}
physicalBio = 100 - (physicalBio * 100);
emotionalBio = 100 - (emotionalBio * 100);
intellectualBio = 100 - (intellectualBio * 100);
System.out.println("Physical compatibility: " + java.lang.Math.round(physicalBio) + " %.");
System.out.println("Emotional compatibility: " + java.lang.Math.round(emotionalBio) + " %.");
System.out.println("Intellectual compatibility: " + java.lang.Math.round(intellectualBio) + " %.");
}
}
You'd rather have your Biorhythm class be something representing the data about a single person. So you'd create two instances of it (call them "one" and "two", say) and make them non-static. It would have instance variables, not static variables, representing name and date of birth.
class Biorhythm {
private Date dob;
private String name;
Biorhythm(String name, Date dob) {
this.name = name;
this.dob = dob;
}
public String getName() {
return name;
}
public Date getDob() {
return dob;
}
}
public static void main(String[] args) {
Date onedob = /* implementation omitted */
Biorhythm one = new Biorhythm("maxval", onedob);
System.out.println("one: name=" + one.getName() + " date=" + one.getDob());
/* and so forth */
}
You don't really have a need for setXXX() methods because these values aren't probably going to change in your program.
Now create two instances of this class in your main() method. I'll leave the implementation of the calculation methods as an exercise for the time being, since there would be several decent designs for implementing them (in terms of the object-oriented question you asked).
First let me explain what these keywords are-
private,default,protected.public are ACCESS SPECIFIERS.
public-as the word says ,can be accessed everywhere and all members can be public.
protected-can be accessed outside the package in case of inheritance.
default-access able within the package and all members can be default.
private-scope lies within the class,cant be inherited.
And remember these can be used with variables,methods,even classes.
static-can be used when there is no need to invoke methods or access variables with objects.
static members doesn't belong to object and initialised at the time of loading a class.
for ex:
class Converter{
public static long convert(long val){
return val;
}
class User{
long value=Converter.convert(500);//calling convert with class name}

get an specific object from my arrayList(Java)

hi my problem is that in my code i am calling a method that calculates the different between 2 point and then if that distance is less that 7 it will call another class method that should change the color of the target to red... my problem is that in my arraylist i have 3 or five or depends on the user input targets... so how can i specify the object in my arraylist that is going to be change of color>??? this is my code
package project1;
import java.util.*;
import javax.swing.*;
/**
*
* #author Elvis De Abreu
*/
public class TargetGallery
{
/**ArrayList of Targets initialize as a private*/
private ArrayList<Target> mytargets = new ArrayList<>();
/**Static object for the Target class*/
static Target tg = new Target();
/**Static object for the RifleSite class*/
static RifleSite rs = new RifleSite();
/**Static object for the TargetGallery class*/
static TargetGallery tgy = new TargetGallery();
/**the number of targets input by the user as private*/
private int number = 0;
/**array that store the distance between 2 point for each target*/
private double[] total;
/**
* Method that build the background of the canvas
* with a picture as a environment
*/
private void buildWorld()
{
StdDraw.setXscale(0, 250);
StdDraw.setYscale(0, 250);
StdDraw.picture(75, 130, "bath.jpeg", 450, 285);
}
/**
* Method that draw a weapon in the middle of the
* canvas as a shooter weapon
*/
private void drawShooter()
{
StdDraw.setXscale(0, 250);
StdDraw.setYscale(0, 250);
StdDraw.picture(125, 0, "weapon.png", 80, 45);
}
/**
* randomly generates X locations for the targets
* add them into the array list
*/
private void createTargets()
{
double x = 125;
double y = 175;
double radius = 7;
String input = JOptionPane.showInputDialog("Type a number" +
"between 2 and 5");
number = Integer.parseInt(input);
for(int i = 0; i < number; i++)
{
Target targ = new Target(x, y, radius);
mytargets.add(targ);
Random rand = new Random();
x = rand.nextInt(400) + 10;
for (Target e: mytargets)
{
if ((e.getX() <= (x+10)) || (e.getX() >= (x-10)))
{
mytargets.clear();
i--;
continue;
}
}
}
}
/**
* Method that run different methods which start the program
*/
public void run()
{
tgy.buildWorld(); //call the buildWorld method
tgy.drawShooter(); //call the drawShooter method
tgy.createTargets(); //call the createTarget method
tgy.simulate(); //call the simulate method
}
/**
* calculates the distance between the RifleSite and the Targets
*/
public void calcDistance()
{
//variable declaration/initialization
double distance;
double distance1;
int i = 0;
total = new double[number];
//for each loop to calculate x and y location of RifleSite and Targets
for (Target e: mytargets)
{
distance = Math.pow(e.getX()-rs.getX(), 2.0);
distance1 = Math.pow(e.getY()-rs.getY(), 2.0);
total[i++] = Math.sqrt(distance + distance1);
}
}
/**
* Method that simulates the game
*/
public void simulate()
{
//Variable declaration/initialization
boolean alive = true;
for(Target e: mytargets)
{
e.drawAlive();
}
rs.drawRifleSite();
//loop that will run while there is still targets alive or user press q
while(alive == true)
{
//if user press a key this
if (StdDraw.hasNextKeyTyped())
{
char ch = StdDraw.nextKeyTyped(); //store the key pressed
//if person press Q will quit the program
if (ch == 'q')
{
int done = JOptionPane.showConfirmDialog(null,
"The Program will close now bye :)");
System.exit(0);
}
else if (ch == 'f')
{
tgy.calcDistance(); //calculates the distance
//if statement to check if the distance if less than radius
for(int i = 0; i < number; i++)
{
if (total[i] <= 7)
{
//THIS IS WHERE MY METHOD SHOULD GO
//SHOULD BE SOMETHING LIKE E.drawDead
}
}
}
}
}
}
/**
* Method for the main of the Program
* #param args the command line arguments
*/
public static void main(String[] args)
{
}
}
Like this:mytargets.get(INDEX GO HERE)
i Hope that helps
(the index starts from 0)
For example:
Target t=mytargets.get(0);
if ((t.getX() > 10) && (t.getY() > 10))
{
//blablabla
}