adding an unknown number of parameters to a method call in Java - java

I have a method that I want to expand (rather than writing a new method which does basically the same thing), by adding an unknown number of parameters to the end of the list of parameters.
If I do this, will I have to change all the calls to the method? I guess the question is, does the unknown parameter include the case there being no parameter passed in at all?
For instance, if I have a method:
queryFactory(int [] typeArgs, int queryType, int[] ... args){}
Could I call:
queryFactory(typeArgsInstce, queryTypeInstce)
And then when I need to add parameters to the query call:
queryFactory(typeArgsInstce, queryTypeInstce, argsInstce)
Where argsInstce is an array of integers containing extra arguments.
I would like to just edit this method rather than writing a new one which does almost the exact same thing except it has some arguments to add to queries. I will simply write another method if by editing this one I will have to change every other call to this method.

public static void main(String[] args) {
method(1); // <- compile error
method(1,2);
method(1,2,3);
method(1,2,3,4);
}
private static void method(int i1, int i2, int...i3) {
// do something
}
So to answer the question in words: we need 2 arguments at minimum. This passes an empty array ´i3[]´ to the method. Arguments number 3 and above are treated as array values.
It makes no difference...
public static void main(String[] args) {
method(new int[]{1}); // <- compile error
method(new int[]{1},2);
method(new int[]{1},2,new int[]{3,4});
method(new int[]{1},2,new int[]{3,4},new int[]{5,6});
}
private static void method(int[] i1, int i2, int[]...i3) {
// do something
}
The varargs parameter has to be the last so it won't conflict with the first array

As you asked Could I call: you can call here is the example
public static void main(String[] args) {
int[] i = { 1, 2, 3 };
int[] i1 ={1,1,1,1};
System.out.println("Sum: " + sum(i,2,i1));
System.out.println("Sum: " + sum(i,2));
}
static int sum(int[] numbers1,int num,int[]... numbers2) {
int t[][] = numbers2;
int total = 0;
for (int i = 0; i < t.length; i++) {
for (int j = 0; j < t[i].length; j++) {
System.out.print(t[i][j]);
total += t[i][j];
}
}
for(int test : numbers1)
total+=test;
total+=num;
return total;
}

I understand that you don't want to change the signature of your method because you will need to change every call of that method, so you could create a method that have the 3 args with all the code, and overload the same method with only 2 args, but in this method you only call the method with 3 args, the last arg will be null. I know is not that you want, but you wouldn't repeat the code and change the signature of the method.
public void queryFactory(int [] typeArgs, int queryType, int... args){
// do something
}
public void queryFactory(int [] typeArgs, int queryType){
queryFactory(typeArgs,queryType,null);
}

Related

Trying to print a method using another method

Not sure where I'm going wrong with this. I've asked someone in my class and they said there should be an argument with "toonRijSterren". when I do this I just get more errors, could someone have a look and tell me where I'm going wrong?
public static void main(String[] args) {
int aantal = 0;
toonRijSterren(aantal);
toonSterrenVierkant(aantal);
}
public static void toonRijSterren(int mpAantal) {
while (mpAantal < 6) {
System.out.print(" * ");
mpAantal++;
}
}
public static void toonSterrenVierkant(int mpAantal) {
for (int mpAatal = 0; mpAantal < 6; mpAantal++) {
System.out.println(toonRijSterren());
}
}
ther error line is in the brackets of the last toonRijSterren());
toonRijSterren is void method which means it does not return any value and therefore you can not put it inside System.out.println() or you can not assign it to some variable.
toonRijSterren expects an int argument which you have missed while calling it.
Given below is an example of how you should call toonRijSterren:
public static void toonSterrenVierkant(int mpAantal) {
for (int mpAatal = 0; mpAatal < 6; mpAatal++) {
toonRijSterren(mpAantal);
}
}
You are not passing the argument when you call your method.
Try this:
System.out.println(toonRijSterren(mpAatal));
First of all, your function toonRijSterren takes an int type parameter (according to its declaration), so you need to pass to it another argument. For example:
toonRijSterren(mpAantal)
Second, the function toonRijSterren returns void. That means, it just does an operation (in this case, printing) without returning anything. What you're trying to do is to use its return value (which doesn't exist) as an argument to System.out.println, which causes an error (because println expects an argument of some type).
You could achieve what I think you're trying to do with the line:
toonRijSterren(mpAantal);.
The function itself prints the values, so the println here is unnecessary and causes an error.
You are missing the parameter in your toonSterrenVierkant() function where you calling toonRijSterren.
Here is the corrected version of your code:
public static void toonSterrenVierkant(int mpAantal) {
for (; mpAantal < 6; mpAantal++) {
toonRijSterren(mpAatal);
}
}
As your methed toonSterrenVierkant(int mpAantal) has a int parameter, you must pass an int value as an argument in the last toonRijSterren(). For example, replace the line System.out.println(toonRijSterren()); with System.out.println(toonRijSterren(1));

Using an array as a parameter

I do not understand the details of using an array as a parameter:
I have created an int array and a method and I do not understand why it's possible to rename the parameter as seen below from "note" to "veraenderung".
How does Java deal with parameters? Do I need a parameter even if I call the method(note)?
public class ArrayParameter {
public static void main(String[] args) {
int[] note = {3,2,1,4,5}; //Array
int[] note2 = {3,2,1,4,5};
korrektur(note);
korrektur2(note2);
}
//Der Methode "korrektur" wird der int Array (note) übergeben!
public static void korrektur (int note[]) {
for (int i = 0; i<note.length; i++) {
//Sobald die for Schleife aufgerufen wird, werden die jeweiligen Werte um -1 reduziert
note[i]-=1;
System.out.println(note[i]);
}
}
//int "veraenderung" ist ein Parameter
public static void korrektur2 (int veraenderung[]) {
for (int i = 0; i<veraenderung.length; i++) {
//Sobald die for Schleife aufgerufen wird, werden die jeweiligen Werte um -1 reduziert
veraenderung[i]-=1;
System.out.println(veraenderung[i]);
}
}
}
i do not understand why it is possible to rename the parameter
korrektur and korrektur2 are just 2 different methods each of them having 2 independent signatures. They are not related whatsoever (even if the programmer can name them alike, just as you did);
The name of the parameters are just local names useful in the method block;
How do java deal with parameter? Do i need a parameter even if i call the method(note)?
Those methods parameters are mandatory ones. Hence you need to insert them in your method call.
I will try to break it down as small as possible for you to understand :)...
When you creating the method. example: public static void korrektur2 (int veraenderung[]) the int veraenderung[] can be named whatever you want...the main thing is that you put the "int []" somewhere within the brackets so that you tell java that "hey my method take an integer array".
The name veraenderung itself is only used locally (within that method) as a reference to tell java whatever you parse into that method will act.
For example when you call the method above and said korrektur(note); . note was declared as an array before, so when you put 'note' inside the method korrektur it is the same as replacing veraenderung with note. In other words java replaces your local variable with the one you passed into the method.
And to answer your question....for now...since you created the method which takes an integer array...YES you must always "put an integer array inside" it when calling the method. I.e. every time you call the method korrektur2 or korrekturand you do not put an integer array inside it, Java would be like "hey I was created to take an integer array and do stuff with it...why are you leaving me empty ?!?!?"
I hope this solved your questions :)
If you have seen the .class file, you'll find the parameters are the same.
you should understand the conception 'vars Scope' (may be this). Parameter 'paramArrayOfInt' have the influence korrektur(), then it be destroied. In next method ,it just new one. It's my understanding. May be wrong, welcome to discuss.
public class ArrayParameter
{
public static void main(String[] paramArrayOfString)
{
int[] arrayOfInt1 = { 3, 2, 1, 4, 5 };
int[] arrayOfInt2 = { 3, 2, 1, 4, 5 };
korrektur(arrayOfInt1);
korrektur2(arrayOfInt2);
}
public static void korrektur(int[] paramArrayOfInt)
{
for (int i = 0; i < paramArrayOfInt.length; i++)
{
paramArrayOfInt[i] -= 1;
System.out.println(paramArrayOfInt[i]);
}
}
public static void korrektur2(int[] paramArrayOfInt)
{
for (int i = 0; i < paramArrayOfInt.length; i++)
{
paramArrayOfInt[i] -= 1;
System.out.println(paramArrayOfInt[i]);
}
}
}

Multiple methods in one program

I'm attempting to have an array (fishWeights) be set to the values that are found using a method. Except that when I try to compile this:
public class GoFishEdited {
public static void main(String[] args) {
System.out.println("\nProject 1, Stage 3\n");
Habitat h1 = new Habitat();
Habitat h2 = new Habitat();
int[] fishWeights = stockUp();
System.out.println("Start with some weights:");
for (int i : fishWeights) {
System.out.print(i + " ");
}
System.out.println("\n\nMake fish of those weights.\n");
Fish[] fishGroup = new Fish[fishWeights.length]; // array of Fish
for (int i=0; i < fishWeights.length; i++) {
fishGroup[i] = new Fish(fishWeights[i]); // make fish
}
}
}
It states that that the symbol stockUp() cannot be found. It is in this file:
public class Habitat {
ArrayList stringer = new ArrayList();
public int maxCount=25;
public int minCount=9;
public int maxWeight=10;
public int minWeight=1;
public int catchProbability=30; //0.3
public void stockUp(int[] fishArr){
int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
for(int i = 0; i<numofF; i++){
fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
}
}
public Habitat(){
}
public void addFish(Fish f) {
stringer.add(f);
}
public void removeFish(Fish f){
stringer.remove(f);
}
public void printFish(){
System.out.println(stringer);
}
}
So stockUp exists, I just can't seem to make getFishEdited to find it.
In java everything in an object.
So if you want to call method form a class should use
Habitat habitat = new Habitat();
habitat.stockUp();
stockUp() is an instance method of the Habitat class, so you need to create an instance of Habitat in your GoFishEdited class's main method in order to call it from GoFishEdited. You could call it on either instance of Habitat created, h1 or h2 Like this:
h1.stockUp();
Note that in the code you posted, you need to pass an array of integers as an argument to stockUp(), but it looks like in your code you are expecting stockUp() to return an int[]. If stockUp() is supposed to return an array of integers, then you need to change the method signature to look something like:
public int[] stockUp() {
//do whatever you want this method to do
return arrayOfInts;
}
You need to either create an instance of habitat using new Habitat to call the method in, or you need to make the method stockUp static and call it in the Habitat class using Habitat.stockUp.
Since you've created instances of Habitat in h1 and h2, call
h1.stockUp(fishArray)
Or
h2.stockUp(fishArray)
depending on what you mean to do. You declared the stockUp() method to accept an int[], so you'll need to pass it one--I called it fishArray, since you seem representing fish. Also, you've declare stockUp() as returning void, so don't expect it to return some value that you can assign to fishWeights. At some point you may find it's a good idea to introduce a Fish class to wrap that concept up better.

How to return a specific element of an array?

I want to return odd numbers of an array yet Eclipse doesn't seem to accept my return array[i]; code. I think it requires returning a whole array since I set an array as a parameter to my method.
As I said before, I need to pass an array and get a specific element of that array in return. Even if I make that array static, how do I return a single element?
Edit : Alright then, here it is:
public class newClass{
public static void main(String[] args)
{
int [] newArray= new int [4];
int [] array = {4,5,6,7};
newArray[0] = array[0]+array[1]+array[2]+array[3];
newArray[1] = array[0]*array[1]*array[2]*array[3];
newArray[2] = findOut(array);
}
public static int findOut (int [] array3)
{
int e1=0;
int e2=0;
for (int i=0; i<array3.length; i++)
{
if (array3[i]%2==0)
{
e1+=array3[i];
array3[i]=e1
return array3[i];
}
else
{
e2+=array3[i];
array3[i]=e2;
return array3[i];
}
}
}
}
I know there are probably more than a few mistakes here but I'm working on it and I'm not only returning odd numbers, I also add them together.
You code should look like this:
public int getElement(int[] arrayOfInts, int index) {
return arrayOfInts[index];
}
Main points here are method return type, it should match with array elements type and if you are working from main() - this method must be static also.
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
Make sure return type of you method is same what you want to return.
Eg:
`
public int get(int[] r)
{
return r[0];
}
`
Note : return type is int, not int[], so it is able to return int.
In general, prototype can be
public Type get(Type[] array, int index)
{
return array[index];
}
(Edited.) There are two reasons why it doesn't compile: You're missing a semi-colon at the end of this statement:
array3[i]=e1
Also the findOut method doesn't return any value if the array length is 0. Adding a return 0; at the end of the method will make it compile. I've no idea if that will make it do what you want though, as I've no idea what you want it to do.

Java: How to pass byte[] by reference?

You can do it in .NET by using the keyword "ref". Is there any way to do so in Java?
What are you doing in your method? If you're merely populating an existing array, then you don't need pass-by-reference semantics - either in .NET or in Java. In both cases, the reference will be passed by value - so changes to the object will be visible by the caller. That's like telling someone the address of your house and asking them to deliver something to it - no problem.
If you really want pass-by-reference semantics, i.e. the caller will see any changes made to the parameter itself, e.g. setting it to null or a reference to a different byte array, then either method needs to return the new value, or you need to pass a reference to some sort of "holder" which contains a reference to the byte array, and which can have the (possibly changed) reference grabbed from it later.
In other words, if your method looks likes this:
public void doSomething(byte[] data)
{
for (int i=0; i < data.length; i++)
{
data[i] = (byte) i;
}
}
then you're fine. If your method looks like this:
public void createArray(byte[] data, int length)
{
// Eek! Change to parameter won't get seen by caller
data = new byte[length];
for (int i=0; i < data.length; i++)
{
data[i] = (byte) i;
}
}
then you need to change it to either:
public byte[] createArray(int length)
{
byte[] data = new byte[length];
for (int i=0; i < data.length; i++)
{
data[i] = (byte) i;
}
return data;
}
or:
public class Holder<T>
{
public T value; // Use a property in real code!
}
public void createArray(Holder<byte[]> holder, int length)
{
holder.value = new byte[length];
for (int i=0; i < length; i++)
{
holder.value[i] = (byte) i;
}
}
For more details, read Parameter passing in C# and Parameter passing in Java. (The former is better written than the latter, I'm afraid. One day I'll get round to doing an update.)
Actually, in Java, the references are passed-by-value.
In this case, the reference is a byte[] object. Any changes that affect the object itself will be seen from the caller method.
However, if you try to replace the reference, for example using new byte[length], you are only replacing the reference that you obtained by pass-by-value, so you are not changing the reference in the caller method.
Here's an interesting read about this issue: Java is Pass-by-Value Dammit!
Here's an concrete example:
public class PassByValue
{
public static void modifyArray(byte[] array)
{
System.out.println("Method Entry: Length: " + array.length);
array = new byte[16];
System.out.println("Method Exit: Length: " + array.length);
}
public static void main(String[] args)
{
byte[] array = new byte[8];
System.out.println("Before Method: Length: " + array.length);
modifyArray(array);
System.out.println("After Method: Length: " + array.length);
}
}
This program will create a byte array of length 8 in the main method, which will call the modifyArray method, where the a new byte array of length 16 is created.
It may appear that by creating a new byte array in the modifyArray method, that the length of the byte array upon returning to the main method will be 16, however, running this program reveals something different:
Before Method: Length: 8
Method Entry: Length: 8
Method Exit: Length: 16
After Method: Length: 8
The length of the byte array upon returning from the modifyArray method reverts to 8 instead of 16.
Why is that?
That's because the main method called the modifyArray method and sent a copied reference to the new byte[8] by using pass-by-value. Then, the modifyArray method threw away the copied reference by creating a new byte[16]. By the time we leave modifyArray, the reference to the new byte[16] is out of scope (and eventually will be garbage collected.) However, the main method still has reference to the new byte[8] as it only sent the copied reference and not an actual reference to the reference.
That should demonstrate that Java will pass reference using pass-by-value.
Java uses pass by value for method arguments.
Primitives (int, boolean, etc.) are special cases in Java.. not objects per se. In this case, a copy of the primitive (argument) is passed into the function. This gels well with the pass by value theory.
For Objects, what happens is that the ref to the object is passed by value (a copy of the reference is made rather than the object)... but both references point to the same object. So if you modify an object parameter in a method, the actual object will be modified.
This article should help you out..
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
As for the OP's question, just pass in the reference to the byte[] array to the method. The net result would be similar to pass by reference. If you modify the byte array, the caller will be able to see the changes post method execution.
Update to quell the resistance :) => indicates output
.NET Land
class Counter
{
private int m_count = 0;
public override string ToString()
{
return String.Format("Counter ID{0} : Value {1}", this.GetHashCode(), m_count);
}
public void Increment()
{ m_count++; }
}
class MakeAPass
{
public void PassByValueAndModify(int i)
{ i = 20; }
public void PassByRefAndModify(ref int i)
{ i = 20; }
public void PassByValueAndModify(Counter c)
{ c.Increment(); }
public void PassByRefAndModify(ref Counter c)
{ c.Increment(); }
public void PassByRefAndReassign(ref Counter c)
{
c = new Counter();
for (int i=0; i<5; ++i)
c.Increment();
}
}
static void Main(string[] args)
{
MakeAPass obj = new MakeAPass();
int intVal = 10;
obj.PassByValueAndModify(intVal);
Console.WriteLine(intVal); // => 10
obj.PassByRefAndModify(ref intVal);
Console.WriteLine(intVal); // => 20
Counter obCounter = new Counter();
obj.PassByValueAndModify(obCounter);
Console.WriteLine(obCounter.ToString()); // => Counter ID58225482 : Value 1
obj.PassByRefAndModify(ref obCounter);
Console.WriteLine(obCounter.ToString()); // => Counter ID58225482 : Value 2
obj.PassByRefAndReassign(ref obCounter);
Console.WriteLine(obCounter.ToString()); // => Counter ID54267293 : Value 5
}
Java Land
Minor mods reqd: Use hashCode() and + to concat strings in Counter.java...
class MakeAPass
{
public void PassByValueAndModify(int i)
{ i = 20; }
// can't be done.. Use Integer class which wraps primitive
//public void PassByRefAndModify(ref int i)
public void PassByValueAndModify(Counter c)
{ c.Increment(); }
// same as above. no ref keyword though
//public void PassByRefAndModify(ref Counter c)
// this can't be done as in .net
//public void PassByRefAndReassign(ref Counter c)
public void PassAndReassign(Counter c)
{
c = new Counter();
for (int i=0; i<5; ++i)
c.Increment();
}
}
public static void main(String args[])
{
MakeAPass obj = new MakeAPass();
int intVal = 10;
obj.PassByValueAndModify(intVal);
System.out.println(intVal); // => 10
//obj.PassByRefAndModify(ref intVal);
//System.out.println(intVal); // can't get it to say 20
Counter obCounter = new Counter();
obj.PassByValueAndModify(obCounter);
System.out.println(obCounter.ToString()); // => Counter ID3541984 : Value 1
//obj.PassByRefAndModify(ref obCounter);
//Console.WriteLine(obCounter.ToString()); // no ref. but can make it 2 by repeating prev call
obj.PassAndReassign(obCounter);
System.out.println(obCounter.ToString()); // => Counter ID3541984 : Value 1
// can't get it to say 5
}

Categories

Resources