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
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;
}
...
}
When we say
public static void task(int number)
{
(you can give any example)
}
what is the function of parameter there ? I understand that when we give task.subtring(0,5) here the parameters are telling us the place value of the character. How does it work in "int"..
If you are confused about the general idea of parameters, they are a message you pass to a method. Think of a method or a function for that matter as a labeled block of code the you can execute somewhere else using that label. Now, parameters are a way of giving a different input to that block of code. They are variables that get used inside that block of code and that you can set from outside of it by passing in a different value when you use that label. For example, I can pass an int (integer number) to a method that multiplies it by 2 and returns the result:
int multiplyBy2(int number){
return number*2;}
Now, I can pass different numbers into that method and get different outputs. What could be confusing about that method you've shown is that it doesn't return a value and can't access class fields, so it might seem useless. However, that method can be doing a lot of other stuff with that integer. A few examples: the method can be printing some string to the screen that changes based on the integer, it could be writing to a file, it could be modifying static fields, and many other possible tasks.
In the example you posted you would pass in the value of a single int; maybe to get a single character, maybe to read a specific line from a file; anything that needs that single int. In the example you understand there are two int parameters.
Your question is for the idea of parameters at all, aren't you? Parameters make methods more dynamic. for example you want to add a number to an existing int in an object. you will do it in this way (it is only a part of a class):
int all;
....
public void add(int i){
all += i;
}
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.
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.
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
So I was wondering if there was good logic behind making the difference between calling on an object's properties and methods explicit.
Obviously, it allows you to have properties and methods that share the same name, but I don't think that comes up much.
The only big benefit I can come up with is readability. Sometimes you might want to know whether something is a method or a property while you're looking at code, but I'm having trouble coming up with specific examples when that would be really helpful. But I am a n00b, so I probably just haven't encountered such a situation yet. I'd appreciate examples of such a situation.
Also, are there other languages where the difference isn't explicit?
Anyways, if you could answer, it will help me be less annoyed every time I make this mistake ^-^.
UPDATE:
Thanks everyone for the awesome answers so far! I only have about a week's worth of js, and 1 day of python, so I had no idea you could reference functions without calling them. That's awesome. I have a little more experience with java, so that's where I was mostly coming from... can anyone come up with an equally compelling argument for that to be the case in java, where you can't reference functions? Aside from it being a very explicit language, with all the benefits that entails :).
All modern languages require this because referencing a function and calling a function are separate actions.
For example,
def func():
print "hello"
return 10
a = func
a()
Clearly, a = func and a = func() have very different meanings.
Ruby--the most likely language you're thinking of in contrast--doesn't require the parentheses; it can do this because it doesn't support taking references to functions.
In languages like Python and JavaScript, functions are first–class objects. This means that you can pass functions around, just like you can pass around any other value. The parentheses after the function name (the () in myfunc()) actually constitute an operator, just like + or *. Instead of meaning "add this number to another number" (in the case of +), () means "execute the preceding function". This is necessary because it is possible to use a function without executing it. For example, you may wish to compare it to another function using ==, or you may wish to pass it into another function, such as in this JavaScript example:
function alertSomething(message) {
alert(message);
}
function myOtherFunction(someFunction, someArg) {
someFunction(someArg);
}
// here we are using the alertSomething function without calling it directly
myOtherFunction(alertSomething, "Hello, araneae!");
In short: it is important to be able to refer to a function without calling it — this is why the distinction is necessary.
At least in JS, its because you can pass functions around.
var func = new Function();
you can then so something like
var f = func
f()
so 'f' and 'func' are references to the function, and f() or func() is the invocation of the function.
which is not the same as
var val = f();
which assigns the result of the invocation to a var.
For Java, you cannot pass functions around, at least like you can in JS, so there is no reason the language needs to require a () to invoke a method. But it is what it is.
I can't speak at all for python.
But the main point is different languages might have reasons why syntax may be necessary, and sometimes syntax is just syntax.
I think you answered it yourself:
One of my most common bugs is that I can never remember whether something is a method or a property, so I'm constantly adding or removing parentheses.
Consider the following:
if (colorOfTheSky == 'blue')
vs:
if (colorOfTheSky() == 'blue')
We can tell just by looking that the first checks for a variable called colorOfTheSky, and we want to know if its value is blue. In the second, we know that colorOfTheSky() calls a function (method) and we want to know if its return value is blue.
If we didn't have this distinction it would be extremely ambiguous in situations like this.
To answer your last question, I don't know of any languages that don't have this distinction.
Also, you probably have a design problem if you can't tell the difference between your methods and your properties; as another answer points out, methods and properties have different roles to play. Furthermore it is good practice for your method names to be actions, e.g. getPageTitle, getUserId, etc., and for your properties to be nouns, e.g., pageTitle, userId. These should be easily decipherable in your code for both you and anyone who comes along later and reads your code.
If you're having troubles, distinguishing between your properties and methods, you're probably not naming them very well.
In general, your methods should have a verb in them: i.e. write, print, echo, open, close, get, set, and property names should be nouns or adjectives: name, color, filled, loaded.
It's very important to use meaningful method and property names, without it, you'll find that you'll have difficulty reading your own code.
In Java, I can think of two reasons why the () is required:
1) Java had a specific design goal to have a "C/C++ like" syntax, to make it easy for C and C++ programmers to learn the language. Both C and C++ require the parentheses.
2) The Java syntax specifically requires the parentheses to disambiguate a reference to an attribute or local from a call to a method. This is because method names and attribute / local names are declared in different namespaces. So the following is legal Java:
public class SomeClass {
private int name;
private int name() { ... }
...
int norm = name; // this one
}
If the () was not required for a method call, the compiler would not be able to tell if the labeled statement ("this one") was assigning the value of the name attribute or the result of calling the name() method.
The difference isn't always explicit in VBA. This is a call to a Sub (i.e. a method with no return value) which takes no parameters (all examples are from Excel):
Worksheets("Sheet1").UsedRange.Columns.AutoFit
whereas this is accessing an attribute then passing it as a parameter:
MsgBox Application.Creator
As in the previous example, parentheses are also optional around parameters if there is no need to deal with the return value:
Application.Goto Worksheets("Sheet2").Range("A1")
but are needed if the return value is used:
iRows = Len("hello world")
Because referencing and calling a method are two different things. Consider X.method being the method of class X and x being an instance of X, so x.method == 'blue' would'nt ever be able to be true because methods are not strings.
You can try this: print a method of an object:
>>> class X(object):
... def a(self):
... print 'a'
...
>>> x=X()
>>> print x.a
<bound method X.a of <__main__.X object at 0x0235A910>>
Typically properties are accessors, and methods perform some sort of action. Going on this assumption, it's cheap to use a property, expensive to use a method.
Foo.Bar, for example, would indicate to me that it would return a value, like a string, without lots of overhead.
Foo.Bar() (or more likely, Foo.GetBar()), on the other hand, implies needing to retrieve the value for "Bar", perhaps from a database.
Properties and methods have different purposes and different implications, so they should be differentiated in code as well.
By the way, in all languages I know of the difference in syntax is explicit, but behind the scenes properties are often treated as simply special method calls.