How can I print a result from a void method - java

I'm doing an assignment for my intro to programming class and it's a bubble sort. The code may be flawed, but I'm not looking for someone to solve that problem. What my problem is, is that I'm trying to print it. I've been given the condition that the method had to be defined by a void method by the line "public static void sort(int[] array)". So, if I tried import Arrays, and used System.out.println(Arrays.toString(sort(array))); in my main method, it wouldn't work because I get a compiler error saying that void does not apply. If I tried to put it into a loop at the main method, it tells me that there are incompatible types. What is found is a void, what is required is an int[], but the original condition of the assignment is to use a void method. So, with that being said, should I change the method from void to int[] for testing purposes and submit the assignment as a void, or is there a way to print the output of this code with the void and I'm just missing it?
public static void sort(int[] array)
{
int[] y = new int[array.length];
for(int i = 0; i<=array.length-1; i++)
{
for(int j = i+1; i<=array.length-1; j++)
{
if(array[i] < array[j]){
y[i] = array[j];
}
if(array[i] >= array[j]){
y[i] = array[i];
}
}
for(int k = 0; k<y.length; k++){
System.out.println(y[k]);
}
}
} //end of sort method

The problem is that you create an new local array inside your sort method which you obviously cannot return because of the restriction of you assignment.
int[] y = new int[array.length];
Your method will not be valid, since the array passed will remain unchanged. You need to do the sorting in place, i.e. without creating a new array. So that if you pass it from your main method, it gets sorted and you can print it there.
Bubble sort should use a swap method, so you just need one temporary variable.

In order to print the array, in your main method you'll need
//code that initializes the array or whatever
sort(myArray);
System.out.println(Arrays.toString(myArray)); //print the array modified by the previous method call
Also note what #A4L said about your local array. Work with the array you pass as parameter to your method, don't create a new one.

Arrays.sort() modifies the array you pass in. So if you iterate over the array object and print the elements AFTER your call to Arrays.sort(), it will print for you.

Since you have a void sort method, you want it to sort the array as a side effect. That is, modify the values in the int[] array reference you passed as a method parameter. Then you can print it from main.

Related

Cannot invoke indexOf on an Array of strings?

I'm writing a method to calculate the distance between 2 towns in a given array by adding all the entries between the indexes of the two towns in the second array, but I can't invoke indexOf on the first array to determine where the addition should start. Eclipse is giving me the error "Cannot invoke indexOf on array type String[]" which seems pretty straight forward, but I do not understand why that won't work.
Please note the program is definitely not complete.
public class Exercise_3 {
public static void main(String[] args){
//Sets the array
String [] towns={"Halifax","Enfield","Elmsdale","Truro","Springfield","Sackville","Moncton"};
int[] distances={25,5,75,40,145,55,0};
distance(towns, distances, "Enfield","Truro");
}
public static int distance(String[] towns,int[] distances, String word1, String word2){
int distance=0;
//Loop checks to see if the towns are in the array
for(int i=0; i<towns.length; i++){
if(word1!=towns[i] || word2!=towns[i] ){
distance=-1;
}
//Loop is executed if the towns are in the array, this loop should return the distance
else{
for(int j=0; j<towns.length; j++){
*int distance1=towns.indexOf(word1);*
}
}
}
return distance;
}
}
No, arrays do not have any methods you can invoke. If you want to find the index of an given element, you can replace String[] by ArrayList<String>, which has an indexOf method to find elements.
It doesn't work because Java is not JavaScript.
The latter offers an array prototype that actually exposes the function indexOf, while the former does not.
Arrays in JavaScript are completely different from their counterparts in Java.
Anyway, you can be interested in the ArrayList class in Java (see here for further details) that is more similar to what you are looking for.
How about this (from this post)?
There are a couple of ways to accomplish this using the Arrays utility class.
If the array is not sorted:
java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search for performance:
java.util.Arrays.binarySearch(theArray, o)
I hope this helps you. If it doesn't, please downvote.

How to return a 2D array using Reflection?

Purpose of Code
To find out what picture is on the screen by comparing it with an already existing set of pixels, which are in the form of methods that return 2D arrays, in the DataStoragePics Class.
How I tried to Solve it
Using reflection I stored all the methods from DataStoragePics class in the methodStorage[].
Then I invoke a method from methodStorage[] which will then store in a tempMatrix[][].
Using a loop and another method (not shown here) I will later use to find out what type of Picture the captured set of pixels are.
What I need help with
When I try to solve the problem by using the steps mentioned above I get an error on the third line from the bottom in the main class repeated twice:
Multiple markers at this line - Type mismatch: cannot convert from Object to int.
I think the problem is methodStorage[x].invoke(DataStoragePicsObj) is a single array but it return a 2D array and the program doesn't recognize that so it needs either the tempMatrix to be a simple array or the methodStorage[] to be a 2D array. I need help solving that error.
This is the Main Class:
import java.lang.reflect.Method;
int [][] tempMatrix = new int[16][450];
//Creates a DataStoragePics Object.
DataStoragePics DataStoragePicsObj = new DataStoragePics();
//Stores all DataStoragePics methods in methods[].
Method[] methodStorage = DataStoragePicsObj.getClass().getMethods();
//Loops through methodStorage[].
for(int x = 0; x < method.length; x++)
{
//Stores a 2D array from DataStoragePics class in tempMatrix.
//All methods in DataStoragePics return a 2D array with [16][10] dimensions.
/*This is the error line*/
tempMatrix[16][10] = methodStorage[x].invoke(DataStoragePicsObj);
/*above is the error line*/
}
This is Part of the DataStoragePics class:
public class DataStoragePics
{
public int[][] picXYZ()
{
int[][] rgbValues =
{
{1,2,3,4},
{9,8,7,6}
};
return rgbValues;
}
}
I am bit of a beginner when it come to java/coding so please don't use complicated terms.
Syllabus's answer helped but I am still getting this error: "Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to [[I" The thing is casting and it stores and returns stuff on the screen. Sometimes it shows the error at the end sometimes in the middle. Don't know why.
You are looping through all the methods in your class. And casting the return value of each of these methods to int[][].
Method[] methodStorage = DataStoragePicsObj.getClass().getMethods();
//Loops through methodStorage[].
for(int x = 0; x < method.length; x++)
This is of course going to fail, because your DataStoragePicsObj class implicitly extends java.lang.Object which has methods like hashCode, toString and getClass that do not return int[][].
If you invoke a method through reflection, you should be prepared to pass it the right arguments and the process it's return value; if you cannot, you shouldn't invoke the method through reflection.
What you could do - if my understanding of what you want to do is correct - is to check the return type and also the arguments to make sure that you are prepared to handle the reflective invocation:
Method m = methodStorage[x];
if (m.getReturnType() != int[][].class || m.getParameterTypes().length != 0) {
// Skip this method because it requires arguments or doesn't return int[][]
continue;
}
Actually, with no "cast", the compiler just considers that invoke return an Object.
tempMatrix[16][10] represents the element (16, 10) in your tempMatrix array, so its type is an int.
So assigning an Object to an int raises a compiler error: types before an after the "=" must be the "same".
First, you must cast the Object returned by invoke to a int[][].
Then you must assign to a int[][] object (the full tempMatrix?)
tempMatrix = (int[][]) methodStorage[x].invoke(DataStoragePicsObj);

Array is not displaying correct values

I am new to java,I have created array which accepts 8 values. It's working fine,also accepting values but it's not displaying correct output on console,please help me what the problem can be ??
Here's my code,
import java.util.*;
public class array2
{
public static void main(String []args)
{
Scanner scan=new Scanner(System.in);
int[] nums=new int[8];
for(int count=0;count<8;count++)
{
nums[count]=scan.nextInt();
}
System.out.println(nums);
}
}
Use System.out.println(Arrays.toString(nums)); (import java.util.Arrays to do this)
If you just say System.out.println(nums);, it will only print the object reference to the array and not the actual array elements. This is because array objects do not override the toString() method, so they get printed using the default toString() method from Object class, which just prints the [class name]#[hashcode] of the object instance.
Printing an array like that is not possible in Java, you probably got something like "[I"...
Try looping:
for (int n=0; n<nums.length; ++n)
System.out.println(nums[n]);
This is because you are printing the array object instead of elements
Use this
for(int i : nums){
System.out.println(i);
}
The [ symbol in the output indicates that the object being printed
is an array.
Alternatively, you can do
System.out.println(Arrays.toString(nums));. This gives String representation of the array.
Display array in a loop:
for(int count=0; count<8; count++)
{
System.out.println(nums[count])
}
You are printing array reference, not their elements.
You need to use Arrays.toString(int[]), to create string that will contain the expected from. Currently you are printing string representation of array itself.
nums[count]=scan.nextInt() will only print the memory location of the array and not the array contents. To print the array contents you need to loop as you did when you insert them. I would try:
for(int count=0;count<8;count++){
System.out.println(nums[count]);
}
Hope that helps

array-element:array-name in Java

Below is an example program from some notes on how to use the for loop in Java. I don't understand how the line element:arrayname works. Can someone briefly explain it, or provide a link to a page that does?
public class foreachloop {
public static void main (String [] args) {
int [] smallprimes= new int [3];
smallprimes[0]=2;
smallprimes[1]=3;
smallprimes[2]=5;
// for each loop
for (int element:smallprimes) {
System.out.println("smallprimes="+element);
}
}
}
It's another way to say: for each element in the array smallprimes.
It's equivalent to
for (int i=0; i< smallprimes.length; i++)
{
int element=smallprimes[i];
System.out.println("smallprimes="+element);
}
This is the so called enhanced for statement. It iterates over smallprimes and it turn assignes each element to the variable element.
See the Java Tutorial for details.
for(declaration : expression)
The two pieces of the for statement are:
declaration The newly declared block variable, of a type compatible with
the elements of the array you are accessing. This variable will be available
within the for block, and its value will be the same as the current array
element.
expression This must evaluate to the array you want to loop through.
This could be an array variable or a method call that returns an array. The
array can be any type: primitives, objects, even arrays of arrays.
That is not a constructor. for (int i : smallPrimes) declares an int i variable, scoped in the for loop.
The i variable is updated at the beginning of each iteration with a value from the array.
Since there are not constructors in your code snippet it seems you are confused with terminology.
There is public static method main() here. This method is an entry point to any java program. It is called by JVM on startup.
The first line creates 3 elements int array smallprimes. This actually allocates memory for 3 sequential int values. Then you put values to those array elements. Then you iterate over the array using for operator (not function!) and print the array elements.

How to copy hashset and hashmap, and does the Java use pointers?

I have two questions:
First:
I have a function which returns a HashMap. To read the returned value, I write it like this:
HashMap<Integer,String> hs=my_func2();
I do the same if the function returns a HashSet.
HashSet<Integer> hs=my_func();
I wanted to know if in this way the returned value is copied into hs, or I should write a deep copy for it or I should write it like this:
HashSet hs=new HashSet(my_func());
HashMap hm=new HashMap(my_func2());
Second quesion:
I make a matrix by calling make_matrix_funciton. matrix woule be a 2-dimensional array containing:
[0 1 1
0 0 0
0 0 0]
Then I give this matrix to sort_vec, and in this function the elements of matrix change. I think java is not pointer based, so when I come out of sort_vec, matrix should be as it had been. But, it has changed! It is
[0 0 0
0 0 0
1 1 0]
which shows the changes that had been applied to it inside the sort_vec function. Is it normal and if yes, what should I do to prevent it. The code below is compilable.
public static void main(String args[]) {
int matrix[][]=new int[3][3];
matrix=make_matrix("011000000");
int indexes[]={2,1,0};
int[][] mat=sort_vec(3,matrix,indexes);
}
private static int[][] sort_vec(int motifsize,int [][]mat,int[] indexes)
{
int[] main_index={0,1,2};
int l=indexes.length;
for (Integer i=0;i<l;i++)
if(indexes[i]!=main_index[i])
{
int j=indexes[i];
int k=main_index[i+1];
for(;k<l;k++)
if(indexes[k]==main_index[i])
break;
indexes[k]=j;
mat=exchange(motifsize,mat,j,main_index[i]);
}
return mat;
}
private static int[][] exchange(int motifsize,int [][]matrix,int x,int y)
{
int temp;
for(int i=0;i<motifsize;i++)
{
temp=matrix[i][x];
matrix[i][x]=matrix[i][y];
matrix[i][y]=temp;
}
for(int i=0;i<motifsize;i++)
{
temp=matrix[x][i];
matrix[x][i]=matrix[y][i];
matrix[y][i]=temp;
}
return matrix;
}
private static int[][] make_matrix(String id)
{
int matrix[][]=new int[3][3];
int c=0;
for(int x=0;x<3;x++)
for(int y=0;y<3;y++)
{
if(id.charAt(c)=='1' || id.charAt(c)=='5')
matrix[x][y]=1;
c++;
}
return matrix;
}
Java always passes Objects by reference, so if you return a HashMap-Object from a function, the reference will be passed to the hs variable in your example. Passing the HashSet to the constructor of a new HashSet instance will not work. It will create a new HashSet with the same object references as in the original one. If you modify one of these objects, the change will appear on all other reference points, too.
If you want to totally detach the copy, you will need your own method for deep copying because in the JavaDoc for the clone() method it says:
Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
The same goes for arrays. Every array is an object, so if you modify an element, it will be modified for all references to this array. To create a deferred copy, use System.arrayCopy
You are misunderstanding how Java's references work.
In the first part, your object will be a reference to a HashMap - i.e., whatever object you've returned from the function
In the second part, you are passing a reference to an int[][], it is not pass by value when it's an array of primitives. Thus, your function will modify the array. If you want a function that does not modify the input array, you need to copy what is passed in to the function or you will need to copy the array before you pass it to your function.
The behavior in Java sorting routines is that they modify the original array.
In sum, there is no way to 'pass by value' an object or array in Java. If you want this behavior, you have to clone (e.g., copy) the object manually or using #user3001's suggestion
Once you figure this out, you may want to read this as well: http://javadude.com/articles/passbyvalue.htm

Categories

Resources