So I'm sorting arrays in subclasses that inherit a couple of methods from a class with things like swap to switch indexes a method to find the minimum value, method to print etc, however for the findMinimum method, my teacher provided us with a pre-made code, but I'm having a little trouble understanding it, was hoping some of you would be able to help.
An array is inserted by the user in a main class
public int findMinimum(int[] array, int first){
int minIndex = first;
for(int i =0; i<array.length; i++){
if(array[i]<array[minIndex]){
minIndex = i;
}
}
return minIndex;
}
What I'm having a hard time understanding is since int first is given no initial value isn't it considered null and therefore can't be used to check in the loop? How can int minIndex be set equal to null?
Thanks in advance
int first is a function parameter, so it will have an initial value when you call this function. You will call it with some array and initial assumed index of min:
myMinimum = findMinimum(myArray, 0)
In this case it actually doesn't make much sense, because minimum of a function will not depend on this parameter. I'd rewrite it as:
public int findMinimum(int[] array){
int minIndex = 0;
for(int i = 1; i < array.length; i++){
if(array[i] < array[minIndex]){
minIndex = i;
}
}
return minIndex;
}
See, I also skip the very first value because it is an initial minimum by default.
When you call this method in your code, you supply an initial value for both array and first, such as this...
public static void main(String[] args){
int[] myArray = new int[]{2,5,10,30};
int theMinimum = findMinimum(myArray,5);
}
The variable first will always have a value, it just depends on what is passed through by the method call. In the example above, the value of first is 5.
Maybe this is where you're getting confused... Your code is a method - it only gets run when you call the method in your code, as in the above example. If you don't call the method findMinimum(), then this code will never be run. The exception to this is your main() method, which is a special method that is understood my the Java JVM as being the entry point, the first bit of code that is run. All other methods need to be called, and passing through the values it requires (in this case, passing through values for array and first)
Related
i have a task to complete. I have to create a return type method takes String array as an argument and returns to int. So my method works completely fine i will use it to count multiple elements of an element in an array but on method name it says "Return value of the method is never used". I just didn't get what am i missing on method. This is my method:
public static int countMultiple(String[] s){
int counter = 0;
for (int i = 0; i < s.length; i++) {
s[i] = s[i].trim();
if (s[i].contains(" ")) {
counter++;
}
}
System.out.println(counter);
return counter;
}
I assume what you mean is not really an error, but rather a warning from your IDE. Your IDE basically wants to tell you, that you return a value with your method (in your case an int value), but never use this value to work with it.
Therefore, the IDE suggests you improve your code, as if you never need the value you could also just return a void value. Therefore you have two ways to solve this issue:
a) In the method from where you call countMultiple(String[] s) you can work with that value, e.g. by simply logging it.
b) If you don't need the value in the caller method, you can return void: public static void countMultiple(String[] s)
For case b, think of removing return counter; from the method as well.
I got this code:
public static ArrayList<Integer> MakeSequence(int N){
ArrayList<Integer> x = new ArrayList<Integer>();
if (N<1) {
return x; // need a null display value?
}
else {
for (int j=N;j>=1;j--) {
for (int i=1;i<=j;i++) {
x.add(Integer.valueOf(j));
}
}
return x;
}
}
I am trying to call it from the main method just like this:
System.out.println(MakeSequence (int N));
but I get an error...
Any recommendations? Much appreciated, thanks!
System.out.println(MakeSequence (int N));
should be
int N = 5; // or whatever value you wish
System.out.println(MakeSequence (N));
Just pass a variable of the correct type. You don't say that it is an int again;
You define the method as follow MakeSequence (int N), this means that method expects one parameter, of type int, and it'll be called N when use inside the method.
So when you call the method, you need to pass an int like :
MakeSequence(5);
// or
int value = 5;
MakeSequence(value);
Then put all of this in a print or use the result in a variable
System.out.println(MakeSequence(5));
//or
List<Integer> res = MakeSequence(5);
System.out.println(res);
All of this code, to call the method, should be in antoher method, like the main one
Change x.add(Integer.valueOf(j)); to x.add(j); as j is already an int
to follow Java naming conventions : packages, attributes, variables, parameters, method have to start in lowerCase, while class, interface should start in UpperCase
The first issue is I think that N should be some int value not defining the variable in the method call. Like
int N = 20;
ClassName.MakeSequence(N);
The other issue you will face. As System.out.println() only prints string values and you are passing the ArrayList object to it, so use it like this System.out.println(ClassName.MakeSequence(N).toString())
Hi and thanks for noticing my problem. I want to write a method that can be used by different types of arrays. But my code always looks like this:
public int indexOf_1(int[] a,int b){
//Find the first matched result and return, otherwise report -1
int index = -1;
for(int j=0;j<a.length;j++){
if (a[j]==b)
{index=j;}
}
return index;
}
public int indexOfChar_1(char[] a,int b){
//Consider merged to the previous method?
int index = -1;
for(int j=0;j<a.length;j++){
if (a[j]==b)
{index=j;}
}
return index;
}
That seems to be redundant and I'm completely uncomfortable with such code duplication. Is there any way to write a searching method for all kinds of array to avoid repeating in this case? Thanks!
Unfortunately because the way arrays and the JVM work, this can't be reduced. Not even generics can help since int[] cannot be safely cast to Object[] without explicit conversion.
This looks like a common util function. If you're not comfortable with the code duplication, you can consider using one of the many libraries which provide this functionality. Guava and Commons-Lang are a few.
Guava puts them in the class relevant to the primitive type. Commons-Lang arranges them in the ArrayUtils class
e.g.
Bytes.indexOf(byteArray, (byte) 2);
Ints.indexOf(intArray, 22);
ArrayUtils.indexOf(intArray, 6);
Well you could use Object[] but you might not want to use ==, since it will compare identity of objects instead of values, instead you probably want to use .equals(). (Unless you know the value will always be a char or int) Perhaps this:
public int indexOf(Object[] a, int b) {
int index = -1;
for (int j = 0; j < a.length; j++) {
if (a[j].equals(b)) {
index = j;
}
}
return index;
}
public static <T> int index_Of(Object[] input,T value){
//Find the first matched result and return, otherwise report -1
for(int j=0;j<input.length;j++){
if(input[j].equals(value))
return j;
}
return -1;
}
You can generalize you method to deal with all kind of arrays. However, please pay more attention to the type. If you want to use Object referring to primitive type, when declaring a primitive type array, you need to use reference type. For example,
Character [] a = new Character[]{'a','b','c'};
DO NOT use char, since it will compile error when type checking.
I am trying to fill a 7x6 blank 2d Array in java with a value of -1.
I initialized the array in a non-main class by typing:
int[][] anArray = new int[7][6];
Then I created a method setArray() which looks like the following:
public int[][] setArray()
{
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 6 ; j++)
{
anArray[i][j] = -1;
}
}
return anArray;
}
but when I run this method through the main class, it returns the board as:
[[I#71988d36
Does anyone know why this is happening? I'm fairly sure the above code is correct.
edit: Forgot a pair of curly braces.
Every class extending Object in Java (that is, all of them) inherits this method:
public String toString()
Which is called when you invoke to decide what to actually print
System.out.println()
The problem is, unless you override it, it will return something not very helpful which will get printed (except in a few cases such as String, int ....).
In this particular case, rather than overriding it, and as the comments above explain, it's easier to call a wrapper function that takes the array as a parameter and delivers a nice String as a result.
I was doing some exercises on arrays, and I was prompted to return a reference to an array after copying it element by element. What does this exactly mean?
My code is the following:
public static int[] cloneArray(int array[])
{
int[] arraycopy = new int[array.length];
for(int i = 0; i < array.length; i++)
{
arraycopy[i] = array[i];
}
return arraycopy;
}
I don't know what I should be returning though as a "reference": should I return an array of ints or an int? Whenever I try to print the array, I get a weird combination of characters and numbers (unless I invoke Arrays.toString()).
"Return a reference to an array" just means "return an array".
Java only returns values, which are either primitives or object references (ie for objects, the value is a reference).
Although Java is based on C, it doesn't sully itself with pointers etc like C does.
In Java, arrays and objects do not act like primitive types such as int. Consider the following code:
public class MyClass {
public static int method1(int ar[]) {
int x = ar[1];
ar[1] = 3;
return x;
}
}
Now suppose that somewhere else, the follow code is executed:
int abcd[] = new int[3];
abcd[0] = 0;
abcd[1] = 1;
abcd[2] = 2;
int d = MyClass.method1(abcd);
System.out.println(abcd[1]);
What would be printed? It's not 1, but 3. This is because the method was not given the data in the array, it was told the location of the array. In other words, it was passed a reference. Because it was using a reference, changing the value of an array index changed its value in the code that called it. This would not have happened if method1 had taken an int as an argument.
Basically, in Java, methods do not accept arrays as arguments or return arrays. They only use references to arrays. The same goes for objects (except for Strings, which are passed by value).
In Java, Objects are only accessed by reference. Just return the Array object.