How to implement overload methods to identify variables correctly - java

I've been working on my project for about 15 hours straight and I ran out of ideas and am in desperate need of some help. I have looked at tutorials and books, but i cannot figure it out.
My main problem is that i cannot understand/calculate how i can use an overload method to choose between an int or a double. To explain I'm trying to get my program to use user input to convert the value to either int to a double (or vice-versa) and store the result to show the correct answers.
Instead of just leaving it as double I'm trying to get the variation for each possibility.
The reason I'm trying to do so is as follows (i know the code doesn't need it but the assignment requires i do so in this way but I keep hitting dead ends) :
Here’s where the overloading comes in: some applications will define the amount as an int, and others will define it as a double. Therefore, you need to write two overloaded versions of this method:
Get user input only once. If you convert the input value for the amount loaned to an int and store it in an int variable, you can then convert the value of this int to a double and store the result of this conversion in a double variable. The use of cast operators to either convert int values to double or double values to int.

Why complicating the situation?
A simple solution:
- Receive the input as double
- Check whether the number is integer. If yes then convert it to integer then call the appropriate method. A quick search give this:
How to test if a double is an integer
Convert double to Int, rounded down

If you need to write two overloaded versions of the interestcalc function, just make two separate methods with the following signatures:
public static void interestcalc (int aLoan, double interes, int numYears)
{
// perform calculations here
}
public static void interestcalc (double aLoan, double interes, int numYears)
{
// perform calculations here
}

Related

BigDecimal math operations

I want to write this in Java but I get some errors and I am not sure how to write it:
C = A - (A*B)/100
All of my values are defined as Bigdecimal objects.
I tried something like this but is not working:
C = A.subtract(A.multiply(B).divide(100));
..I get a warning to add more arguments to the divide method. I do not know how to write it correctly. What am I doing wrong? Thanks in advance
BigDecimal has no divide(int) method, but that's what you're asking it to do with .divide(100), because 100 is an int literal. If you refer to the documentation, all of the divide methods accept BigDecimal instances.
You can use divide(BigDecimal) instead, by using BigDecimal.valueOf:
C = A.subtract(A.multiply(B).divide(BigDecimal.valueOf(100)));
(It accepts a long [or double], but int can be promoted to long.)
Alternately, for some values, you might use the String constructor instead:
C = A.subtract(A.multiply(B).divide(new BigDecimal("100")));
...particularly if you're dealing with floating-point values that might lose precision in double. 100 is fine for valueOf, though.
c = a.subtract(a.multiply(b).divide(BigDecimal.valueOf(100.0)));

How can I convert something to double?

I have an object from an implemented class ReportManager. Now getReport() is a number like 0.23 with the data type report. But I want this number to be a double so I can work with it.
I cannot change the class, because it is implemented in the Java compiler (it is for writing macros for a program).
Does anybody have a suggestion how I could handle it? I checked the API and there is no function implemented that could help me.
EDIT: I do have the situation: I want to calculate the Center of Pressure of an object in my simulation. So I need the moment in that position to be 0.
Now: This is how the automated macro ask the value of the Moment:
MomentReport momentReport_0 =
((MomentReport) simulation_0.getReportManager().getReport("Moment 1"));
Now I want to take the abs of it, because I don't mind if it's positive or negative.
while(Math.abs(momentReport_0) > 0.2)
(Do iterate and change position.) At the end I want to println the the position.
simulation_0 is an object of Simulation. I could copy a part of the API if it's needed. Just don't know which class documentation would help.
You can cast the number to a double so that you can work with it, assuming it's returning you a single-precision float at the moment.
double result = (double) reportManager.getReport();
I recommend you read up on what typecasting is so that you can better understand what's going on here, as there would be some situations where it's unsafe to cast:
https://en.wikipedia.org/wiki/Type_conversion

Android:how to get a value from a RSS feed and subtract it from a value in another RSS feed

Hey i have these two RSS feeds - http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=kilmarnock and http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow. Now what i want to do is take a value from one RSS feed and calculate it with a value from the other RSS feed. So for example
132.9 - 133.1
How would i go about doing this?
The basic idea is that the user creates the RSS URLs and then the onClick takes all the values from each of the RSS feeds and compares it against the other so that the user gets the difference so the overall money saved by selecting one or the other
To my understanding, your question has a simple answer, and a more specifically helpful answer. I'll state the simple answer of how to convert character data to a number (whether an int, double, float, etc.) first for the record, specifically focusing on the exception cases, then delve into the detail that specifically applies to your problem.
Any time you have a String representation of something you believe is a certain type of number, you can call the appropriate valueOf() or parseXYZ() method for the target wrapper class. E.g. if you're looking for an integer: theInt is the String "42". Integer.valueOf(theInt) would return an Integer with the value 42, and Integer.parseInt(theInt) would return int 42.
http://developer.android.com/reference/java/lang/Double.html
If theInt represented, say, "forty-two" or "42.0" either method would throw NumberFormatException. Parsing a floating-point number follows much the same process, except that "42.0" would parse correctly, and "42.0.0" will throw a NumberFormatException on Android. The whole string passed to one of these methods must be a valid number of the chosen type. Whitespace at the end will also throw the exception.
If you're using a Scanner, you can use hasNextXYZ() and nextXYZ() to check for and get the next number, where XYZ can be any of the primitive types. The Scanner will operate on the next token, which it will define based on the delimiters you have set.
http://developer.android.com/reference/java/util/Scanner.html
"Great, so when, where, and how should one take the numbers in the XML and pass them to any of the above methods?" You should have a data structure to hold each value, which you populate as the XML is being parsed. Based on the state of things over at your related question, it is my understanding that parsing the XML into tokens has been solved. Therefore, update your parser to call the right String-to-number conversion method for the values of highest, average, and lowest elements. The Strings you need are already correctly trimmed and are passing through the parser at each stage.
Or, to decouple your code further, create an object the hold the data sets you will be comparing, then have the parser simply instantiate and call setters. FuelData could be that object.
class FuelData {
String KEY_TYPE;
double highest;
double average;
double lowest;
// if future support for currency types needed, would go here, hook in to units attribute in xml
FuelData(String type) { // call this every time a type is encountered parsing html
KEY_TYPE = type;
}
void setHighest(String val) { // here, val is value of "Highest" element
try {
highest = Double.parseDouble(val); // because you're not using a Scanner to parse
} catch (NumberFormatException e) {
// handle appropriately
}
// perhaps sanity check: disallow negatives, check not less than lowest, etc.
}
// and so on for average and lowest
double computeSavings(FuelData pricesB) { // called by onClick
// your subtraction goes here. Perhaps you decide it's reasonable to use this method
// to compute savings for Regular vs. Premium and therefore do not check type,
// perhaps you decide that's illogical and do check types.
// Note: good arguments can be made that this method should exist in a different
// class. I've placed it here for simplicity's sake.
}
}
Collect the FuelData in a logical way, that can be accessed after parsing has finished, such as feed1 being parsed into a Set of FuelData, feed2 to a set of FuelData, etc, then have onClick take all the FuelData that was parsed out of each of the RSS feeds, do the comparisons via computeSavings, and return the results.

Clarifying this Java "Activity" from "SamsTeachYourself Java"

In the book "SamsTeachYourself Java" there is a task that goes like this:
"Write a Java application that takes an argument as a string, converts it to a float variable, converts that to a Float object, and finally turns that into an int variable. Run it a few times with different arguments to see how the results change."
Could someone clarify this text, especially the first part about a java application that takes an argument as a string?
In Java programs start with
public static void main(String[] args){
args is a variable of type String[] (an array of Strings). You can call call functions like args.length() which will return the number of arguments made to the program.
This array is populated with the things that follow the name of the program when you call it. For example if you called your program like:
java MyProgram ate my dog
The variable args would have length three and contain the values "ate", "my", "dog". The following lines would all return true.
args[0].equals("ate");
args[1].equals("my");
args[2].equals("dog");
These other answers will also help explain this
What is "String args[]"? parameter in main method Java
args.length and command line arguments
In IDE like Eclipse you don't type the command that executes these lines but you can configure your project to run with a predetermined set of values. For how to do this in eclipse see this other answer: Eclipse command line arguments
Following the input of a String that represents a float (ex. "1.98") Java contains a number of useful functions for parsing strings into other types. Many of these are contained in classes which wrap the primitive types. One of these is the object type Integer which contains a function called parseInt which takes a String as an argument and returns an int. Similar classes exist for other primitive types as well, including doubles and floats.
Variables of these types can be constructed from their corresponding primitive types. Here is the online documentation of these constructors for the Integer class.
Finally the problem asks you to convert a float to an int. In java you can call a type cast operation like so:
float a = 8.88;
int b = a; //error, loss of precision
int c = (int)a;
When typecasting a float or a double to an int the value is not rounded, it is truncated. In my example above the variable c has a value of 8, not 9.

Java string to double conversion

I've been reading up on the net about the issues with handling float and double types in java. Unfortunately, the image is still not clear. Hence, i'm asking here direct. :(
My MySQL table has various DECIMAL(m,d) columns. The m may range from 5 to 30. d stays a constant at 2.
Question 1.
What equivalent data-type should i be using in Java to work (i.e store, retrieve, and process) with the size of the values in my table? (I've settled with double - hence this post).
Question 2.
While trying to parse a double from a string, i'm getting errors
Double dpu = new Double(dpuField.getText());
for example -
"1" -> java.lang.NumberFormatException: empty String
"10" -> 1.0
"101" -> 10.0
"101." -> 101.0
"101.1" -> 101.0
"101.19" -> 101.1
What am i doing wrong? What is the correct way to convert a string to a double value?
And what measures should i take to perform operations on such values?
EDIT
This is the code -
System.out.println(dpuField.getText());
Double dpu = new Double(dpuField.getText());
System.out.println(dpu);
Yes, the problem lies with getText() reporting the wrong value of the dpuField.
This method is called on the JTextField keyTyped event. So what's going wrong here?
EDIT 2
Looking at :
http://journals.ecs.soton.ac.uk/java/tutorial/post1.0/ui/keylistener.html
Apparently, keyTyped() does not give me the keycode. I'll have to switch to keyRealeased()
What equivalent data-type should i be using in Java to work (i.e store, retrieve, and process) with the size of the values in my table? (I've settled with double - hence this post).
Since it's a DECIMAL field, you should prefer java.math.BigDecimal. You can store it in DB using PreparedStatement#setBigDecimal() and you can retrieve it from DB using ResultSet#getBigDecimal().
While trying to parse a double from a string, i'm getting errors
This can't be true. The problem lies somewhere else. Maybe it is just not returning the data you expect to be returned or you are not using/debugging the values you expect them to be.
if you need exact precision without rounding errors, you should use a BigDecimal.
Your code looks OK - could it be that dpuField.getText() somehow cuts the last character from the string values you list above?
Update: you say
Yes, the problem lies with getText() reporting the wrong value of the dpuField. This method is called on the JTextField keyTyped event.
Could it be that getText() returns the value of the field before the last typed key is actually appended to it?
For decimal, I believe you risk losing precision if you don't use a BigDecimal on the Java side, as some decimal fractions can't be stored as a binary fraction.
Prefer Double.valueOf(String) over the constructor, but that's a valid way. Something else must be going on (i.e. I doubt those are the actual String values you're passing in).
Question1: It's bad idea to map DECIMAL columns to Double, usually the BigDecimal is the correct type. http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html#1055175
Question 2: You are doing something wrong; print the String value before converting.

Categories