Novice: Items set to zero - java

I've just been coding for the past few months, and am just getting started on Java.
I'm getting these weird error messages when I'm testing some of my code.
In one of my exercises, I have this class WeatherRecord. I define it like this:
class WeatherRecord {
Date d;
double precipitation;
TemperatureRange today;
TemperatureRange normal;
TemperatureRange record;
WeatherRecord(Date d, double precipitation, TemperatureRange today,
TemperatureRange normal, TemperatureRange record) {
d = this.d;
precipitation = this.precipitaiton;
today = this.today;
normal = this.normal;
record = this.record;
}
Seems dandy. I also have some comments and methods, but I left those out.
Then, later on in my examples, I make an example, like this:
WeatherRecord record2 = new WeatherRecord(this.date2, 0.24,
this.temp2, this.tempNormal, this.coldTemp);
Where date2, temp2, and all that stuff are previously defined.
I then use a tester library just to check to make sure that precipitation is set to 0.24 (since one of my methods wasn't working earlier, so I was checking):
boolean test(Tester t) {
return t.checkExpect(this.record2.precipitaiton, 0.24);
}
And my console tells me that the actual value was 0.0, rather than .24. I'm consistently getting this sort of error on a lot of different exercises.
Does anything immediately stand out to y'all that I am doing wrong? Is there any more information I should provide?
Thank you!

d = this.d; this chunk of code should be the other way around. this.d = d;
as well as the others.
this.var means the object's var while the variable you receive into the method or constructor doesn't start with this

Related

How to send values through methods

I am stumped trying to send a value through some methods as part of a question which reads
Write the following method: computeDiameter: This method accepts the radius (r) of a circle, and returns it's diameter (2*r)
It's under the "Passing values through different methods", so instead of asking me for a simple variable/formula like
double r;
double diameter = r*2; //along with Scanner and some System out prints
It's asking me to send the value of r through another method, then return the method and print out the new value for r. This is what I have so far
import java.util.*;
public class UserSquares
{
public static void main(String[] args)
{
int r = 2;
int result=0; //I set result=0 hoping to initialize it properly.
computeDiameter(r);
System.out.println(result);
}
public static int computeDiameter(int r)
{
int result = r * 2;
return result;
}
}
This question seemed very simple which is why i tried to tackle it. I know the basics of sending values through a method, but i don't know how to return them. I don't really have money for actual text books (so i settle for quizlet questions and stuff like that), and youtube videos don't help at all so I like coming to the forums to get help when I am really stumped but want to move on with other topics.
(this question is part of a java self test, just thought I should share that as I've asked a number of questions on this site and each time someone responds with something negatively as if I am trying to get you guys to complete my homework for me. I am not taking any Java classes, these questions are just self testing my skills so that when I do major in java programming after i finish highschool, I can have a pretty nice understanding of it. Again, this is not for a test, I am welcome to all types of explanations, as long as it is in the realm of comprehension for a beginner Java student. Please and thank you in advance)
EDIT: Thanks Guys. Immediately after I submitted this I worked on it some more and found a solution so i'll share it
new code
import java.util.*;
public class UserSquares
{
public static void main(String[] args)
{
int total, r = 2;
total = computeDiameter(r);
System.out.println(total);
}
public static int computeDiameter(int value1)
{
int result;
result = value1 * 2;
return result;
}
}
EDIT #2: Holy crap I didn't expect to receive so many solutions so quick. Was about to answer it myself so that it would appear to be done. Sorry for the waste of your time guys, I will read every one of them to see the different solutions you guys offered and learn them so that your time isn't totally wasted. Thanks so much.
EDIT #3: Had a redundant line remaining from my first code that I forgot to take out that went through the compilation and didn't affect the outcome in anyway, but still decided to take it out. Thanks CodeMatrix!
As I said in the comment section.
Go ahead and change this
int result = 0;
computeDiameter(r);
System.out.println(result);
to this
int result = 0; //or you use int result = computeDiameter(r);
result = computeDiameter(r);
System.out.println(result);
its very simple:
int result = computeDiameter(r);
or just
System.out.println(coputeDiameter(r));
You have to assign the value which is being returned from computeDiameter(r) method to the result variable in order to print that.
result = computeDiameter(r);
System.out.println(result);

JButton not sending action command

I am working on a school project and I'm having a dickens of a time trying to get the JButton to do..well.. anything! this is my code, I don't know how important the other .java files are.
I started with a simple code that worked but after adding and editing it can't seem to update the text exactly how I want it.
<removed>
var1, var2, etc. that are being passed in are stored as such..
they are all in another .java file
the Function.fun
<removed>
Okay...
Don't rely on static, it's not going to help you and will create a whole lot of new issues which will be difficult to solve
The main problem is, your code is generating a NumberFormatException - java.lang.NumberFormatException: For input string: "javax.swing.JSpinner[,8,6,109x26,invalid,layout=com.apple.laf.AquaSpinnerUI$SpinnerLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777536,maximumSize=,minimumSize=,preferredSize=]"
So, based on the exception, it's obvious that Double.parseDouble isn't getting the value it excpects
So, having a deeper look at your code...
if (jspValue1.getValue() instanceof Double) {
s = jspValue1.toString();
d = Double.parseDouble(s);
return d;
} else {
return 0.00;
}
You're passing the result of jspValue.toString to Double.parseDouble, but he fact is, it's just not required.
You've already determined that the value from the JSpinner is a double, so you on;y need to cast it...
double value = 0.00d;
if (jspValue1.getValue() instanceof Double) {
value = (Double)jspValue1.getValue();
}
return value;

JFreeChart TimeSeries array exception

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.

Why does to assign a method return makes application run faster than just calling it?

today i was running some test to get a deeper understanding of which some instruction i have in my program, when i notice something unexpected.
I run the following test to understand if it was slower using the BigDecimal pow method and then converting, or converting to double and using the Math.pow.
public static void main(String[] args){
BigDecimal myBd = new BigDecimal(2);
Date start = new Date();
System.out.println("inizio: " + start.toString());
for(int i=0; i++<10000000;){
Math.pow(myBd.doubleValue(),2);
}
Date t1 = new Date();
System.out.println("test 1 in:" +(t1.getTime() - start.getTime()));
for(int i=0; i++<10000000;){
myBd.pow(2);
}
Date t2 = new Date();
System.out.println("test 2 in:" +(t2.getTime() - t1.getTime()));
for(int i=0; i++<10000000;){
double wtf = Math.pow(myBd.doubleValue(),2);
}
Date t3 = new Date();
System.out.println("test 3 in:" +(t3.getTime() - t2.getTime()));
for(int i=0; i++<10000000;){
double wtf = myBd.pow(2).doubleValue();
}
Date t4 = new Date();
System.out.println("test 4 in:" +(t4.getTime() - t3.getTime()));
}
Here is a single output example:
test 1 in:1268
test 2 in:1358
test 3 in:1049
test 4 in:1308
Ok i found that it is better to convert and then using Math pow but... Wait, why the hell test1 is slower than test3 and in a similar way test 2 is slower than test4?
Running this more and more it is always the same. If i assign the returned value, it takes lesser then just calling the method.
Anyone does know the reason?
Below are my personal views , correct me if i am wrong .
I am not sure how accurate my answer will be , I saw the question tried it and now i have some view
BigDecimal
BigDecimal.pow method source code
private volatile BigInteger intVal;
.
.
.
public BigDecimal pow(int n) {
if (n < 0 || n > 999999999) {
throw new ArithmeticException("Invalid operation");
}
// No need to calculate pow(n) if result will over/underflow.
// Don't attempt to support "supernormal" numbers.
int newScale = checkScale((long) scale * n);
this.inflate();
return new BigDecimal(intVal.pow(n), newScale);
}
Observations :
Each call to pow method creates a BigDecimal object
main calculation is done via intVal.pow(n) => BigInteger.pow (check return statement of BigDecimal pow code above)
Every BigInteger.pow creates a new object of BigInteger.pow (internal working of BigInteger.pow have been skipped)
now summary for BigDecimal
EACH call to BigDecimal.pow creates the following major objects (other calculation seemed to be minor)
[in Java source code implementation of BigDecimal]
two new temporary BigInteger
one new temporary BigDecimal
for each call to pow we have 3 new temporary objects of subclasses of java.lang.Number(BigDecimal,BigInteger extent Number) created , this looks like a good point to compare in terms of time taken to run the code
Math.pow
Math.pow method source code
public static double pow(double a, double b) {
return StrictMath.pow(a, b); // default impl. delegates to StrictMath
}
this uses StrictMath's static method pow , the source code can be found here in line 1511 of this link code was huge so i didnt paste here .
Observations :
static methods of Double class is used (i doubt that will lead to a major increase in execution time)
lot of operations on primitive types are used (that also should take less time to run)
my personal view/conclusion would be
BigDecimal creates a lot of objects when it executes the .pow method , which might be the reason of excessive time taken to execute
Accuracy of calculation of both methods is something beyond my knowledge and experience , so ill try explore on accuracy soon and update this answer

Programming exercise?

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?

Categories

Resources