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.
Related
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())
So I'm working on an implementation of a Grid class for a small, personal utilities library. After much work, I'm tidying up the Grid class and adding some functionality. One of the key pieces of functionality that I wish to use with my Grid class is to be able to take a single, 2D array of any given type as an argument to the constructor.
This worked fine until I realized that I can't compile any code that attempts to pass in any array of primitives to the constructor. Since autoboxing doesn't happen on primitive arrays, this presents a design problem to me in the form of code reuse. The method for initializing the Grid is the same regardless of the type of array passed in, even if they are primitives, but it appears that I need to write a separate constructor for all the different types of primitives. Which leaves me with 9 different constructors assuming I just use my base constructor (and I had planned to have constructors with different arguments for things such as grid-wrapping options).
Am I right in assuming that there is no way to avoid all this code duplication?
You can avoid (most of) the duplication by using Array class. But it's not pretty: your constructor parameter would have do be of type Object, and you'd have to just trust your caller to pass the actual array there, and not a Socket or a Properties.
For example, you could do your own boxing like this:
<T> public T[][] boxArray(Class<T> clazz, Object array) {
int height = Array.getLength(array);
int width = height == 0 ? 0 : Array.getLength(Array.get(array, 0));
T[][] result = (T[][]) Array.newInstance(clazz, height, width);
for(int i = 0; i < height; i ++) {
Object a = Array.get(array, i);
for(int j = 0; j < width; j++) {
result[i][j] = (T) Array.get(a, j);
}
}
return result;
}
I'm trying to write this method as a static method but I don't fully understand how static methods work past them not creating objects to work with.
This is the method I'm trying to convert
public void process(String str)
{
for (int i=0; i<str.length(); i++){
char letter = str.charAt(i);
int index = Character.toLowerCase(letter-'a');
if (index>=0 && index<26){
counts[index]++;
}
}
}
This method just takes a string and records the number of times each letter showed up in the String
Im trying to write this as a static method and I have this method stub
public static LetterCounter buildCounter(String str)
{
}
Since this is a learning exercise, I wouldn't write any code, but describe what needs to be done:
Create a new instance of LetterCounter
Call an instance method process on it, passing str that you got in your buildCounter
Return the instance of LetterCounter that you created in step 1.
You are done!
Your current code would require that counts[] be declared as static also, meaning there is only one counts[], and every time you call MyClass.process("blah") it would increase the class variable counts[index]
I am guessing but I think what you are trying to do is create a static "utility' function to return an array of counts for the various charactors in the passed in string? So something similar to this (untested) code.
then you would call something like MyUtilClass.process("xxyz");
In this case "static" means that the process does is not associated with an object, it is more like a "function" or "subroutine"
public static int[] process(String str) {
int[] counts = new int[25];
for (int i=0; i<str.length(); i++){
char letter = str.charAt(i);
int index = Character.toLowerCase(letter-'a');
if (index>=0 && index<26){
counts[index]++;
}
}
return counts;
}
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)
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.