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]);
}
}
}
Related
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));
this may seem daft i have a class called ship locations which i wish to store all my ships locations, ive extended it from my client class and simply called the set method as follows
sub.local being a multidimensional array from the ship class
sub.local = new int[2][2];
sub.local[0][0] =row;
sub.local[0][1]=col;
sub.local[1][0]=row;
sub.local[1][1] =col+1;
toServer.writeInt(row);
toServer.writeInt(col);
toServer.writeChar('s');
sub.placed=true;
setp1sub(sub.local);
When i print it back through another class it comes back with the location in the memory rather than the numbers i need. What is the reason for this
public class ShipLocations {
static int [][] p1sub;
public ShipLocations()
{
p1sub = new int[2][2];
}
public int[][] getp1sub()
{
return p1sub;
}
public void setp1sub(int[][] local) {
for (int i = 0;i <local.length;i++)
{
for(int j = 0;j<local.length;j++)
{
p1sub [i][j]= local[i][j];
}
}
}
}
would it be that im passing it as sub.local ?
output is [[I#a401c2
Instead of writing
System.out.println(yourArray);
use
// for multidemensional arrays:
System.out.println(Arrays.deepToString(yourArray));
// or for one dimemsional arrays:
System.out.println(Arrays.toString(yourArray));
Here is a link to the relevant JavaDoc.
For an explanation of your output, you can look at this answer.
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);
}
Need help on calling a method from main class.
I need to call a method, thus I made an object to handle it.
below I quote my main method
public static void main(String[] args) {
// TODO code application logic here
SLRatio sl= new SLRatio();
sl.clustering(apa);
}
and here's the method I need to call
public class SLRatio {
public static String [][]clustering(String[][]apa) {
System.out.println("Cluster 1");
int a = apa.length/3;
String [][] cluster1=new String [a][apa[0].length];
for (int i =0; i<a; i++) {
for (int j=0;j<apa[0].length;j++) {
cluster1 [i][j] = apa[i][j];
}
}
for (int b = 0; b < cluster1.length; b++) {
for (int c = 0; c < cluster1[0].length; c++) {
System.out.print(cluster1[b][c] + "\t");
}
System.out.println("");
}
System.out.println("\n");
return cluster1;
}
}
and I got error message:
"Cannot find symbol,Accessing static method clustering"
What can I do to solve it? I have tried to change the syntax but it didn't work.
Thank you so much.
you didn't define method Allocation() in SLRatio
Note: static method should be called with classname (to avoid confision between instance method and static)
If it is static method, you don't need to call it through instance.
SLRatio .clustering(...);
should be enough.
And it seems you forgot to implement Allocation method.
Another suggestion, java naming convention, method name starts with small case letters.
Do not use static unless you are sure it is appropriate.
This is a popular programming error, partially because eclipse keeps on suggesting to make variables and methods static when they cannot be accessed. But usually, this is not the correct solution. While it fixes the compilation problem, it often breaks the application logic.
Right now, your problem probably is that apa has type String[][], but you are passing a String[] parameter to it. So it cannot be compiled, because there is no method clustering(String[] args).
Seriously, you need to learn more Java basics. Maybe from a book.
Ok, here is the code and then the discussion follows:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop,
the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same "experiment" with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the currentRow array. Move that inside the row loop and it should behave more like you expect.
Specifically, the assignment in setCurrentRow does not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the same int[] array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.
i don' t want to sound condescending, but always try to remember tip #26 from the excellent pragmatic programmer book
select isn't broken
it is very rare to find a java bug. keeping this in mind often helps me to look over my code again, turn it around, and shake out the loose bits until i finally discover where i was wrong. of course asking for help early enough is very encouraged, too :)