I got this exercise, is not a homework, I just trying to solve:
We manage a farm with horses that have
to work on the field.
A horse has
a name,
a maximum amount of
working hours per week,
the amount
of hours actually worked and
a field to indicate if she is lazy or
hard-working.
All the attributes of the Horse class
are private and they have no setters.
Initial values are passed through the
constructor.
The Horse class has a method to add
one hour of actual work. That method
is called every hour (that the horse
works). At the begin of the next week,
we reset that counter to 0, by calling
another method taking no parameter.
A lazy horse cannot work more than 34
hours/week, while a hard-working horse
can work up to 80 hours.
Code a Horse class that is shielded
against wrong working hours data.
Your main method will create an horse
and call its methods, but the data
must never be corrupted, ie. the
working hour limits must be respected.
For example, a lazy horse's maximum
hours cannot be set above 34 and the
number of hours worked cannot be
greater than the maximum.
If the Horse class detects an attempts
to set incorrect data, the data
remains unchanged (and you print a
message to help you debugging).
Example of correct data:
Name: "Blacky"
lazy: no
max hours / week = 70
actual hours this week = 61
Name: "Sultan"
lazy: yes
max hours / week = 30
actual hours this week = 1
Example of corrupted data (your code should make such a situation impossible to reach)
Name: "Georges"
lazy: yes
max hours / week = 50 (wrong because lazy horses work max 34h/week)
actual hours this week = 51 (wrong because 51 > 50).
This is my code:
public class Horse {
private String name;
private int maximumAmount;
private int amountWorked;
private boolean isLazy;
public Horse(String name, int maximumAmount, int amountWorked, boolean lasyOrHardworking) {
this.name = name;
this.maximumAmount = maximumAmount;
this.amountWorked = amountWorked;
this.isLazy = lasyOrHardworking;
}
void everyHour(){
amountWorked = amountWorked + 1;
System.out.println(amountWorked);
if((isLazy == true)&&(amountWorked <= 34)){
resetToZero();
}
if((isLazy == false)&&(amountWorked <= 80)){
resetToZero();
}
}
void resetToZero(){
this.amountWorked = 0;
}
}
and my main class
public class MainHorse {
public static void main(String args[]){
Horse one = new Horse("Blacky", 34,35,true);
one.everyHour();
}
}
my question is how can I get that my method everyhour do the reset method, and in general, what is wrong in my code?
I hoper you can help me
My question is how can I get that my
method every hour do the reset method,
and in general, what is wrong in my
code?
Try to come up with something with java.util.Timer
Minor details:
Typos and spelling inconsistencies will come back to bite you someday (less likely in Java than in languages that do not require explicit declaration), you should stick to one correct spelling of the word "lazy".
this.isLazy = lasyOrHardworking;
Why not use isLazy in the parameter as well, instead of lasyOrHardworking
this.isLazy = isLazy;
I think bool == true isn't adding any value, this looks better to me:
if(isLazy && (amountWorked <= 34))
I think what you are doing wrong is calling resetToZero() from inside the everyHour() function.
I would have every hour return a bool to indicate success or failure. If failure, it doesn't increment the horse's amount worked, but prints the debug message. The main code could then check to see if it is violating the horses limits. The main code would also call resetToZero when the week ended.
You're not supposed to go back to zero, just not to increase the hoursworked. Also, if this isn't homework, you have some freedom, so I would not have independent variables for max hours and lazy - that just gives you an opportunity to get them out of sync. I would use named constants for maxLazyhours and maxHardworkinghours.
Then have a function called IncrementHours that just says
if (lazy && hours < maxLazyhours) || hours < maxHardworkinghours)
hours++;
It's simpler, right?
Related
I wrote some code:
public class digitShow {
public static void main(String[] args) {
System.out.println(digitShow(98198187));
}
public static int digitShow(int num) {
if (num != 0) {
System.out.print(num % 10);
return digitShow(num / 10);
} else
return num;
}
}
The code works perfectly fine, but I am trying to make it so instead of printing the numbers in reverse order one by one, the output rather would display each digit one by one in the order that they are entered in the parameter.
So in this case:
1
2
3
4
I've been trying to un-reverse it, but I've had no luck.
Ok, some people on comments are suggesting using arrays or similar. This is correct, however this seems like a question made by someone who is learning recursion (and, as a teacher, I can smell a homework question here).
I will not post the answer because I'd be doing your homework for you and we need good programmers in this world. If I (or anyone else) do your homework you'll never understand the basic concepts of programming, and never becoming a good programmer.
Now, building on top of smac89's comment:
Your code to reverse has an issue: it prints 0 after it reverses the digits. Why? because you are returning an integer and then printing it in your main function but you are not really using the return value anywhere else.
Try calling your method without the System.out.println in main and see what happens.
So, basically, evaluate if you really need to return an integer and, if you don't, you can now evaluate how you are calling the recursion (again, read smac89's comment).
I wish you the best in your studies!
You need to reduce the number by successive divisions first. Then process the values as they are unwound from the stack. This will print the most significant to least significant digit. Then return the starting number.
public static int digitShow(int num) {
if (num > 10) {
digitShow(num/10);
}
System.out.println(num%10);
return num; // returns the starting number.
}
prints
9
8
1
9
8
1
8
7
98198187
So, the question is. If I'm calling method guess from class - Player and it is a void-type method without return statement in it, how come I'm able to store result of number = (int)(Math.random() * 10) in number variable for 3 different objects (p1, p2, p3)?
I'm little confused about when should I use return statement or void-type methods, because if number = (int)(Math.random() * 10) is giving some results which I want to use, why then I don't need to return this results from a method to pass them to the number variable which I declared in int number = 0;
public class Player {
int number = 0;
public void guess() {
number = (int)(Math.random() * 10);
System.out.println("I'm guessing " + number);
}
}
A void method does not return anything, but it still allows you to do things. (Print to the console, modify variables etc) The void keyword just means that it doesn't return a value. (In void methods you can still use a blank return; to end the method) And because you are modifying your number variable in the GuessGame object the changes you make will stay even though you don't return a variable. Try this simple test to see what I mean:
//In your GuessGame class
int number = 0;
public void foo() {
number++;
}
public static void main(String[] args) {
GuessGames games = new GuessGames();
games.foo();
System.out.println(games.number);
//Outputs 1
}
docs for the return statement
The point is: where is the result of Math.random() * 10 physically stored on your computer when your program is run? You list two options.
Options 1: Instance field
In this case the compiler instructs your operating system to reserve space for a int variable for the whole life of the Player object. The player object may live for microseconds, seconds, minutes, hours, days, months, ... it depends! This storage space is usually find in the RAM of the computer and from Java you can access it with the syntax myPlayer.number as long as you have a Player reference somewhere.
Options 2: Return value
In this case the compiler finds the space to store the result of the computation in a register of the Java virtual machine, that you can mentally map to a register of the physical processor. This value will only at best survive for a couple of processor cycles (there are gazillinos in a GHz CPU, so it's really a tiny little fracion of a second) if you don't store it somewhere else - and if you don't it's lost forever. See the following example:
private int someRandom;
private int gimmeARandom() {
return Math.random() * 10;
}
private int test() {
int someRandom = gimmeARandom(); // --> store the value until end of method
this.someRandom = someRandom; // --> further keep it so we can read it later
gimmeARandom(); // --> what did it returned? We'll never know
}
Void is different than static - void just means the function does not return anything, but it can still be a instance method, i.e. one that is associated with each new instance of a class. I think you're confusing this with the functionality of static, which allows methods to be called without an instance of the class.
I want to limit the calls to a function within one day.
The problem is I'm a bit confused of how to use the Date and Calendar classes...
private int usesLeft //Set every day to the number of uses
private void function() {
if(usesLeft > 0) {
//Function's body...
}
usesLeft--;
}
I need to find out when a new day starts in order to reset the usesLeft variable.
Well I found a solution...
The better side of this solution is that the user can't "cheat" because then he'll lose activity days (If my analysis of the code behavior is right).
if(lastDayActive < (int)Math.floor(System.currentTimeMillis()/86400000)) {
usesLeft = 100;
//Initializes the day value
lastDayActive = (int)Math.floor(System.currentTimeMillis()/86400000);
}
If there's any way to prevent the user from manually changing the date and therefore gaining more uses I'd really like to hear about it.
this is my first question here ever, and I would appreciate if you can help me.
Since the code I have is way too large to post here, I'll try to describe what my problem is in short.
So, I have made TimeSeries array within my class and array list from where I get values for time series:
private TimeSeries[] seriesArray = new TimeSeries[10];
ArrayList<TempClass> valuesFromArrayList = new ArrayList<>();
I need to make TimeSeries array, because I want to be able to show multiple timeseries graphs. Using only one TimeSeries and addOrUpdate method isn't what I want because then values get mixed when I create more graphs. So, I add values like this:
for(int i = 0; i < valuesFromArrayList.size(); i++)
{
TempClass obj = (TempClass) valuesFromArrayList.get(i);
int timeStamp = obj.getTimeStamp();
int hrsDiff;
int minsDiff;
int secsDiff;
hrsDiff = timeStamp / 3600;
timeStamp = timeStamp - hrsDiff * 3600;
minsDiff = timeStamp / 60;
timeStamp = timeStamp - minsDiff * 60;
secsDiff = timeStamp;
seriesArray[Integer.parseInt(comboBoxValue) - 1].add(new Second(secsDiff, minsDiff, hrsDiff, day, month, year), Math.abs(obj.getValue()));
}
What this part of code does is that it reads values and timestamps from ArrayList I created. There is comboBox where user can choose which timeSeries array index will be in graph. So, if user chooses value 9 from comboBox, timeSeries from index 8 will be chosen and plotted on graph. TimeStamp is simply number of seconds that passed since 00:00:00 at day when values were taken.
TempClass is defined as:
class TempClass
{
private int timeStamp;
private double value;
public TempClass(int a, double b)
{
timeStamp = a;
value = b;
}
public int getTimeStamp()
{
return timeStamp;
}
public double getValue()
{
return value;
}
public void setValue(double val)
{
value = val;
}
}
The problem I have is that when I try to make second (2nd) graph, that is another index of TimeSeries array, I get message:
You are attempting to add an observation for the time period Thu Apr 30 00:00:00 CEST 2015 but the series already contains an observation for that time period. Duplicates are not permitted. Try using the addOrUpdate() method.
I don't want to use addOrUpdate method, I need add method. Values in ArrayList I use to put values into timeSeries are fine, I am 300% sure. I already checked input from comboBox value and it gives correct values.
I have no explanation other that for some reason, even if array index is changed, data I want to write into the series goes to the old series (that is, to the series at the old index). In other words, it seems like even if I change index of array, it keeps writing into the old array index!
It's like equivalent to this (I know this sounds crazy but that is basically what I am getting):
int[] array = new int[5];
array[0] = 1;
array[1] = 2;
System.out.println(array[0]);
And the output I get is
2
This is something I have never heard of before, and I have code similar to this I wrote here in two other places, and in that two places it goes just fine, but in this third place I keep getting that exception.
Is this some kind of bug in JVM?
Does somebody know what this could be?
I don't know too much about TimeSeries, but after skimming the docs about it it says:
"The time series will ensure that (a) all data items have the same
type of period (for example, Day) and (b) that each period appears at
most one time in the series."
Link to Docs
I'm guessing the error is pretty straight forward or a misuse of TimeSeries. It looks like you are simply adding a duplicate date and that the constraints of TimeSeries don't allow that.
You may wish to consider writing a custom class that has the functionality you want. Yet again, I don't know much about TimeSeries, but I hope this helped a little.
Your for loop will always overwrite the value with an index of 0 on seriesArray.
What I mean is, the first time it will write to [0]
The second it will write to [0] then [1]
Is this intended?
I have not looked at the docs too much, but the message says 'the series already contains an observation for that time period.' I think that loop is not doing what you want it to do.
Alright so I'm taking an AP Computer Science course and up until now I've found the content easy and unchallenging because I already had a background in Java. However now I have run into an issue with some of the code that the course is providing me with and writing a function based off of it. I've googled it, and tested many different things to try and get it to work and to no avail. So hopefully you guys can shed some light on this and perhaps help me figure it out.
First the book provides me with this code as a basic Time class:
public class Time extends Object {
private int itsHour;
private int itsMin;
/** Create an object for the given hour and minute. If min
* is negative, adjust the values to make 0 <= min < 60. */
public Time (int hour, int min) { // constructor
super();
itsHour = hour;
for (itsMin = min; itsMin < 0; itsMin = itsMin + 60) {
itsHour--;
}
} //=======================
/** Return the time expressed in military time. */
public String toString() {
if (itsHour < 10) {
return ("0" + itsHour) + itsMin;
} else {
return ("" + itsHour) + itsMin;
}
}
/** Return the result of adding this Time to that Time. */
public Time add (Time that) {
// Read below at issue #2
}
}
That was the main class they gave us to work with and then they gave a class called TimeTester which is to be used to execute the commands. The comments dictate what should happen.
import javax.swing.JOptionPane;
class TimeTester {
public static void main (String[] args) {
Time t1 = new Time (13, 25);
Time t2 = new Time (8, -150);
JOptionPane.showMessageDialog (null, "1 " + t1.toString());
JOptionPane.showMessageDialog (null, "2 " + t2.toString());
Time t3 = t1.add (t2);
JOptionPane.showMessageDialog (null, "3 " + t3.toString());
t1 = t2.add (t3);
JOptionPane.showMessageDialog (null, "1 " + t1.toString());
System.exit (0);
} //=======================
}
Now like I said this code was literally handed to me it's making sense of the code and getting it to work for me that I just literally cannot do. So below are basically the key issues I'm running into.
1) I understand how its supposed to run and what the executors do, but I do not understand what exactly its doing to achieve the results.
2) The add function in the first set of code which was basically it's main class is the main part of the assignment. The assignment reads as follows:
Exercise 4.15 (harder) Write the Time method public Time add (Time
that): The executor returns a new Time object that is the sum of the
two, e.g., 0740 add 1430 is
2210. If the sum is more than 2359, drop the extra 24 hours, e.g., 1300 add 1400 is 300.
Assigned from: http://www.cs.ccsu.edu/~jones/chap04.pdf
When I carry over the values to the add function in the TimeTester executing "now.add(wait)" I go to pull that result using "that" but the values don't pull forward.
I've also tried to change up the functions to perhaps get my own understanding and make it work for me. I changed the Time later call in the TimeTester, and then edited the function add to accept 2 values. Then added this code to the add function:
public Time add (Time time1, Time time2) {
String t1String = time1.toString(); // Value is: "0730"
String t2String = time2.toString(); // Value is: "0245"
int t1convert = Integer.parseInt(t1String, 2); // Value is 730
int t2convert = Integer.parseInt(t2String, 2); // Value is: 245
int total = t1convert + t2convert; // Value added together is: 1015
return total; // Return value of total
}
So my call looked like this:
public static void main (String[] args) {
now = new Time (7, 30); // 7:30 in the morning
wait = new Time (2, 45); // 2 hours 45 minutes
later = now.add (now, wait); // produces 10:15 in the morning
JOptionPane.showMessageDialog(null, now + " + " + wait + " = " + later.toString());
System.exit (0);
}
However all that code would not compile and produce a result which could be returned to my TimeTester, it always produced a compile error of "incompatible types" referring to my return total; line. So it obviously cannot return Integers. So I am just absolutely stuck on what to do to make it add the two times.
3) I cannot use the built in Java time functions where it's formatted with semicolons. I know how to do that part which is why this different way is driving me up the wall.
4) I don't want you to write my code for me, I'd like to gain a better understanding of it and perhaps have my mistakes pointed out so that I can comprehend what in the world is going on with it.
I know it's a long post, but when I ask for help I like to be descriptive and provide everything I can because I know it's going to help me better in the long run and hopefully help the person who helps me track down an answer fast.
(PS. All of this is compiled and ran in a program called BlueJ. It's an online course so I have no instructor in class to ask about it all we have is a monitor.)
Consider a method to add two Time instances (a and b) and return a new Time instance; such a method would look like the inverse of the provided Time constructor loop, for (itsMin = min; itsMin < 0; itsMin = itsMin + 60), specifically - it should increment some hours count (perhaps by adding the hours from a and b) while the number of minutes is > 59 and subtracting 60 minutes at a time... This method might look something like this
public static Time add(Time a, Time b) { // Add two Time(s) together.
if (a == null) { // if a is null, just return b.
return b;
} else if (b == null) { // if b is null, just return a.
return a;
}
int hours = a.itsHour + b.itsHour; // Add the hours together.
int minutes = a.itsMin + b.itsMin; // Add the minutes together.
for (; minutes > 59; minutes -= 60) { // Increment hours as necessary, while
// decrementing the minute count by 60.
hours++;
}
return new Time(hours, minutes); // Return the new Time instance.
}
public static void main(String[] args) {
Time now = new Time(7, 30); // 7:30 in the morning
Time wait = new Time(2, 45); // 2 hours 45 minutes
Time later = Time.add(now, wait); // produces 10:15 in
// the morning
System.out.println(later);
}
Outputs
1015
The compiler is complaining that you are returning an int, when you defined the function return type to be "Time":
public Time add (Time time1, Time time2) {
String t1String = time1.toString(); // Value is: "0730"
String t2String = time2.toString(); // Value is: "0245"
int t1convert = Integer.parseInt(t1String, 2); // Value is 730
int t2convert = Integer.parseInt(t2String, 2); // Value is: 245
int total = t1convert + t2convert; // Value added together is: 1015
return total; // Return value of total
}
The return type is Time:
public Time add (Time time1, Time time2) ...
You return "total", which is of type "int":
int total = t1convert + t2convert;
return total; …
What you would need to do is to make a new Time object which has the answer stored inside of it. For example:
Time t3 = new Time(0, total); // This is assuming that "total" represents the minutes
Regarding the issue in the comment,
#Mike'Pomax'Kamermans Looking at your comment i managed to write this
line of code to see if i could execute it that way and I cannot. "Time
t1 = new Time(this.hour, that.hour); " spits out "cannot find symbol -
variable hour". Any insight into this? – user1686765 3 mins ago
"this.hour" is looking at the current Time instance, which is a instance of the Time class, for a member variable called "hour." If you go to your Time class, you will see that it only has some methods and 2 variables called "itsHour" and "itsMin". So it cannot find the variable "hour" because it does not exist. I think you meant to put "this.itsHour" in place of "this.hour".