I have a method that takes 5 double values and performs an action with them. Right now the argument list is five different doubles. Is there any way to pass a double[] as an argument to the method but make sure its length is exactly 5?
One way is this:
private void myMethod(double[] args) {
if (args.length == 5) {
// do something
}
}
but is there a better way?
If you know you need exactly 5 doubles, then I think you are better off asking for 5 distinct doubles. Having them listed out with meaningful names it will still be hard enough (even with intellisense or whatever it's called) to keep the order of the variables straight. If they are in an array, the user will need to consult the documentation to see which value should go in which index.
No. You can't restrict the length of an array passed to a function.
If your goal is to keep the checking code out of the method so it's cleaner, you could delegate the real work to another method.
If your concern is the length of the parameter list you could pass a parameter object.
You could create a class which is a specialization of a Vector limited to 5 doubles, but it seems like overkill. I would just throw an exception if there are too few or too many entries in the array - this is likely a programming problem rather than a runtime exception.
You could put your code in try-catch block. This provides to miss an unnecessary check.
But if something doing wrong you could avoid the problems with exception.
Related
I've read other questions on this and they're not quite as general as I want this discussion to be.
My question is as stated: What's the simplest approach to making a basic calculator, say with precedence on its operations, and maybe even brackets?
Every time I try to do this, my code gets way more complicated than I usually expect it to.
My usual approach is to take the string input of the calculated request, and then manipulate it. This creates all sorts of problems as I now have to work around the fact that I am using a string rather than some sort of executable Java code.
This is what I generally end up trying to do, regardless of the language I end up using:
Read input string.
Split the string apart into numbers, brackets, and operators.
Interpret each string of digits into a number with class integer.
Create a map from each operation to a method that computes it. Use this to interpret each operator. Then invoke the method on its inputs.
Create a recursive function with several components. First, the empty string. Second, a single character. Third, a single operation. Fourth, deal with no brackets under precedence. Fifth, go by all set of evaluations in each set of closed set of brackets over and over, recursively calling the function itself whenever necessary, until a single constant is returned.
In addition, for the purpose of Java, how do I invoke a method? Every time I try to do this, I seem to be running into problems. If I want to invoke the addition method add and input numbers 2 and 4, say from another class called Arithmetic, how would I go about this? Mainly, I'm unsure as to what goes into the first input for Java's specific case.
add.invoke(__, {1, 1});
I may be calling the invoke method all wrong to begin
To anyone that has tried to build a calculator, has everyone had this much complexity? Is there a simpler way to go about this?
Any discussion here would be great, to be honest.
Edit. I'll clarify how I've defined my add function personally when trying to do this:
public class Arithmetic {
...
public static float add(float x, float y) {
return x+y;
}
...
}
The problem is as follows:
I have to write a program using static methods which according to what the arguments are like need to return a certain type of information.
if the arguments are 2 int-type numbers then it would return the sum of those 2
if one of the arguments is a double-type number then it would return that number squared
if the arguments are a string and an in-type number then it would print said string times the int-type number.
The problem is that I do not know how exactly this program should look like since there's just one "sample" problem about static methods and that one is nothing like the one I'm being asked to solve.
In addition I still haven't figured out why I even need to use this static method if instead
I could simply write an if sentence instead.
Feels kind of bad to not to be able to figure this out myself but I guess sometimes how have to ask for help.
Anyways thanks in advance!
Okay so unless I have misunderstood the question want you want to do is overload a method. As a single method in can only accept a fix set of parameters, the way around this would be to create multiple methods (static or otherwise) with the same name but different parameters.
E.g.
static int method(int a, int b) {
return a + b;
}
static double method(double b) {
return b*b;
}
And so on for each different set of parameters required. However I would recommend also looking up this concept thoroughly as its very fundamental.
To add further, an if statement most likely wouldn't evaluate the parameters inside the function correctly most likely be a lot more cumbersome to program than simply overloading your method to accept different types of parameters and act upon them accordingly
As part of my AP curriculum I am learning java and while working on a project I wondered which of the following is best way to return a value?
public double getQuarters(){
return quarters;
}
or
public void getQuarters(){
System.out.println(quarters);
}
***Note: I now that the second option is not "technically" returning a value but its still showing my the value so why bother?
Your answer would be correct. The second method doesn't return any value at all, so while you might be able to see the output, your program can't. The second method could still be useful for testing or even for a command line application, but it should be named something like printQuarters instead.
public double getQuarters(){
return quarters;
}
Use this incorder to encapsulate quarters and hide it from being accessed by other programs. That means, you have to declare it as private quarters. Let see the second option:
public void getQuarters(){
System.out.println(quarters);
}
However, this seems wrong as getQuarters is not returning anything. Hence it would make more sense to refactor it as
public void printQuarters(){
System.out.println(quarters);
}
You answered your own question. For most definitions of the word "best", you should go with the first option.
Your question, however, does touch on the object-oriented programming topic of accessors and mutators. In your example, "getQuarters" is an accessor. It is usually best to use accessors to retrieve your values. This is one way to adhere to the Open/Closed Principle.
Also, the Java community has a coding convention for this and many tools and libraries depend on code following those conventions.
If all you need to do is display the value when this method is called, and you are ok with console output, then your System.out.println method will do the job. HOWEVER, a function that actually returns the variable is much more semantically correct and useful.
For example, while you may only need to print the variable for your current project, what if you came back later and decided that you were instead going to output your variable to a file? If you wrote your getQuarters function with a println statement, you would need to rewrite the whole thing. On the other hand, if you wrote the function as a return, you wouldn't need to change anything. All you'd have to do is add new code for the file output, and consume the function where needed.
A returning function is therefore much more versatile, although more so in larger code projects.
You return values to a specific point in your program, so that the program can use it to function.
You print values at a specific point in your program, so that you as an end user can see what value you got back for some function.
Depending on the function - for instance, yours - the result of quarters is no longer regarded in the program; all it did was print a value to the screen, and the application doesn't have a [clean|easy] way to get that back to use it.
If your program needs the value to function, then it must be a return. If you need to debug, then you can use System.out.println() where necessary.
However, more times than not, you will be using the return statement.
Option 1 is far superior.
It can be easily Unit Tested.
What if the spec changes and sometimes you want to print the result, other times put it into a database? Option 1 splits apart the logic of obtaining the value from what to do with it. Now, for a single method getQuarters no big deal, but eventually you may have getDimes, getEuros, etc...
What if there may be an error condition on quarters, like the value is illegal? In option 1, you could return a "special" value, like -1.0, or throw an Exception. The client then decides what to do.
For example given the following methods:
public double[] getCoord(){
return coord;
}
public double getCoord(int variable){
return coord[variable];
}
Would it be better to call
object.getCoord()[1]
or
object.getCoord(1)
and why?
Although there is no performance difference, the second method presents a far superior API, because Java arrays are always mutable. The first API lets your users write
object.getCoord()[1] = 12.345;
and modify internals of your object behind your back. This is never a good thing: even a non-malicious users could do things you never intended, simply by mistake.
In terms of performance, it doesn't matter. The first method returns a reference to the array, not a copy.
That said, the second method protects the array from being modified outside the class.
No, Java doesn't read the whole array when you use the subscript operator ([]). With regards to would it be better to use the accessor method to grab the array first, then index into it versus call a method that does the same thing, it's probably negligible. You're still incurring the overhead (minimal mind you) of invoking a function and returning a result either way.
I am going to guess that #2 is marginally slower because a parameter has to be pushed onto the stack prior to the call to getCoord(int). Not much in it though.
Neither has to read the whole array.
Both are slower than direct array access, for example coord[1].
Given the need to loop up to an arbitrary int value, is it better programming practice to convert the value into an array and for-each the array, or just use a traditional for loop?
FYI, I am calculating the number of 5 and 6 results ("hits") in multiple throws of 6-sided dice. My arbitrary int value is the dicePool which represents the number of multiple throws.
As I understand it, there are two options:
Convert the dicePool into an array and for-each the array:
public int calcHits(int dicePool) {
int[] dp = new int[dicePool];
for (Integer a : dp) {
// call throwDice method
}
}
Use a traditional for loop:
public int calcHits(int dicePool) {
for (int i = 0; i < dicePool; i++) {
// call throwDice method
}
}
My view is that option 1 is clumsy code and involves unnecessary creation of an array, even though the for-each loop is more efficient than the traditional for loop in Option 2.
At this point, speed isn't important (insert premature-optimization comment ;). What matters is how quickly you can understand what the code does, which is to call a method dicePool times.
The first method allocates an array of size dicePool and iterates through its values, which happens to run the loop body dicePool times (I'll pretend you meant int instead of Integer to avoid the unrelated autoboxing issue). This is potentially inefficient for the computer running the code, but more importantly it's inefficient for the human reading the code as it's conceptually distant from what you wanted to accomplish. Specifically, you force the reader to think about the new array you've just made, AND the value of the variable a, which will be 0 for every iteration of the loop, even though neither of those are related to your end goal.
Any Java programmer looking at the second method will realize that you're executing the loop body dicePool times with i 'counting up' to dicePool. While the latter part isn't especially important, the beginning is exactly what you meant to do. Using this common Java idiom minimizes the unrelated things a reader needs to think about, so it's the best choice.
When in doubt, go with simplicity. :D
Why would you need to allocate an array to loop over a variable that can be safely incremented and used without any need of allocation?
It sounds unecessarily inefficient. You can need to allocate an array if you need to swap the order of ints but this is not the case. I would go for option 2 for sure.
The foreach is useful when you want to iterate on a collection but creating a collection just to iterate over it when you don't need it is just without sense..
(2) is the obvious choice because there's no point in creating the array, based on your description. If there is, of course things change.
What makes you think that the for-each loop is more efficient?
Iterating over a set is very likely less efficient than a simple loop and counter.
It might help if you gave more context about the problem, specifically whether there's more to this question than choosing one syntax over the other. I am having trouble thinking of a problem to which #1 would be a better solution.
I wouldn't write the first one. It's not necessary to use the latest syntax in every setting.
Your instinct is a good one: if it feels and looks clumsy, it probably is.
Go with #2 and sleep at night.