Printing value at array index returns hashcode - java

Just playing around with displaying values in a two dimensional array and noticed my code prints some hashcodes and then the values. But I am not printing the array object itself (as done in the post here) or at least explicitly calling the toString or hashcode method of the array object. Instead, I'm directly accessing and printing the values in the array using arrayObj[i] and arrayObj[i][j].
Here's my code:
class PrintTwoDimArray {
public int [][] createArray () {
int counter = 0;
int[][] intArray = new int [2][4];
for (int i = 0; i < intArray.length; i++) {
for (int j = 0; j < intArray[i].length; j++) {
intArray[i][j] = ++counter;
}
}
return intArray;
}
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.print(arrayObj[i] + " ");
for (int j = 0; j < arrayObj[i].length; j++) {
System.out.print(arrayObj[i][j] + " ");
}
System.out.println();
}
}
}
class TestPrintTwoDimArray {
public static void main (String[] args) {
PrintTwoDimArray twoDim = new PrintTwoDimArray();
int [][] multiArray = new int [2][4];
multiArray = twoDim.createArray();
twoDim.printArray(multiArray);
}
}
My output is as follows:
It seems that my code is somehow calling the toString or hashcode method of the array. Thoughts? How can I modify to print just the values?
javac and java version 1.8.0

A two dimensional array is an array of arrays. The array you create (int[2][4]) looks like this
[ 0 ] -> [ 1, 2, 3, 4 ]
[ 1 ] -> [ 5, 6, 7, 8 ]
So when you only access the first dimension you will get the array that holds the second dimension.
int[][] arr = createArray();
System.out.println(arr[0]);
will output something like
[I#1db9742
To print an array's values you can use Arrays.toString(arr). In this case you can omit the inner loop, because Arrays.toString() will do it for you.
public void printArray ( int [][] arrayObj ) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.println(Arrays.toString(arrayObj[i]));
}
}

The hash values come from your first System.print sentence.
System.out.print(arrayObj[i] + " ");
With this sentence you are printing an Object (an array) and therefore Java is invoking the default toString method.

When you print
arrayObj[i]
you get the default Object toString() from an array. You could use Arrays.toString(int[]) to make that a String like
System.out.println(Arrays.toString(arrayObj[i]));
Alternatively, you can use Arrays.deepToString(Object[]) to print your multi-dimensional array without a loop
System.out.println(Arrays.deepToString(arrayObj));
Edit
You could use formatted output to build your table.
public static void printArray(int[][] arrayObj) {
for (int i = 0; i < arrayObj.length; i++) {
System.out.printf("%03d: ", i + 1);
for (int val : arrayObj[i]) {
System.out.printf("% 4d ", val);
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] table = { { 3, 1, 2 }, { 5, 1, 4 }, { 100, 200, 300 } };
printArray(table);
}
Output is
001: 3 1 2
002: 5 1 4
003: 100 200 300

Related

Print out the numbers from the for loop

The Return type is void
No input parameters
Print out the numbers calculated results separated by a space using current number add the next number from 0 to (a+b).
An example would be if the numbers for the for loop are 0,1,2,3,4,5,6 then it would add 0+1, 1+2, 2+3, 3+4, 4+5, 5+6 and print out those values just like 0,1,2,3,4,5,6.
I honestly have no clue how to do this so I'm not going to lie about it so can someone help me code it and explain or just help me with it.
public class ForFogMe
{
public int a, b;
public String str;
public void addUp(){
for(a = 0; a <= 6; a ++){
System.out.print(a);
}
String s = Integer.toString(a);
System.out.println();
System.out.print(s.substring(0,2) );
}
public static void main(String args[]){
ForFogMe me = new ForFogMe();
me.addUp();
}
}
If you only want to print sum of the numbers from 0 to 6 you would do it simply like this:
public void addUp() {
for(a = 0; a < 6; a++) {
System.out.print(a+(a+1) + ",");
}
System.out.print("\b"); // to delete last comma
}
In first iteration a is 0 a+1 is 1 so you print their sum like (a+(a+1) + ",") which outputs "1,". It repeats until it reaches 6. At the end we have 1,3,5,7,9,11, so I used System.out.print("\b"); to delete last char, so we get 1,3,5,7,9,11
I believe this should do the trick:
public static void addUp(){
final int[] array = {0,1,2,3,4,5,6};
int[] result = new int[array.length-1];
for(int i = 0; i < array.length-1; i++) {
result[i]=array[i]+array[i+1];
}
result[3]=array[array.length-1];
for(int i = 0; i < result.length; i++) {
System.out.print(result[i]+" ");
}
}
Test case (array):
0,1,2,3,4,5,6
Outputs:
1 3 5 6 9 11
Note: The array size does not matter.

How to check array and compute a number from it?

I have an array and inside its filled with marks for students. However I cannot display the array contents as I keep receiving a reference code or something. I am now trying to check each index in the array and compare it to the pass mark of 40. When I do use an if statement I can never print the [i] afterwards, all help would be appreciated.
public class Exammarks {
public static void main(String[] args) {
int i = 0;
int [] studentmarks = new int[] {45,60,70,21,95,35,83,80,5,41,40,25};
for(i=1;i < studentmarks.length; i++); {
if (studentmarks[i] < 40)
System.out.println(studentmarks[i]);
}
}
}
try to use for each loop
int [] studentmarks = new int[] {45,60,70,21,95,35,83,80,5,41,40,25};
System.out.println("studentmarks size = " + studentmarks.length);
for(int marks : studentmarks) {
System.out.println("marks = " + marks);
if (marks < 40)
System.out.println("marks less than 40 = " + marks);
}
The Array index starts from 0 whereas you have initialized for loop from 1.
int [] studentmarks = {45,60,70,21,95,35,83,80,5,41,40,25};
for(i=0;i < studentmarks.length; i++)
{
if (studentmarks[i] < 40)
{
System.out.println(studentmarks[i]);
}
}
Also, there was ; at the end of for(i=1;i < studentmarks.length; i++);, which means, scope of for loop end there and below part of the code doesn't come under for loop scope.
{
if (studentmarks[i] < 40)
{
System.out.println(studentmarks[i]);
}
}
You can do this more easily by creating a Stream from the array, filtering out the numbers less than 40 and either converting the stream back to an array if you need or just print the result. For example:
int [] studentmarks = new int[] {45,60,70,21,95,35,83,80,5,41,40,25};
Arrays.stream(studentmarks)
.filter(m -> m < 40)
.toArray();
// [21, 35, 5, 25]
Or if you just need to print the result:
Arrays.stream(studentmarks)
.filter(m -> m < 40)
.forEach(System.out::println);

Sorting 2D array in ascending order using java with respect to first row alone

This is for row based sorting
Before sorting: array[2][n]
5 4 3 2 1..
3 4 5 9 0..
After sorting:
1 2 3 4 5..
0 9 5 4 3..
i.e Array should be sorted using 1st row alone in ascending order and corresponding column values should change accordingly as shown in above result.
Guide me how this can be generated using Arrays.sort(a, new Comparator() function?
int rowcount= jTable1.getRowCount();
int j;
int parr[][] = new int[10][10];
for(j=0; j<rowcount; j++)
{
parr[0][j]= Integer.parseInt(jTable1.getValueAt(j, 2).toString());
parr[1][j]= Integer.parseInt(jTable1.getValueAt(j, 1).toString());
}
System.out.println("Before sorting");
for(j=0; j<rowcount; j++)
{
System.out.println(parr[0][j]);
}
for(j=0; j<rowcount; j++)
{
System.out.println(parr[1][j]);
}
System.out.println("After sorting");
Arrays.sort(parr, new Comparator<int[]>()
{
#Override
public int compare(int[] o1, int[] o2)
{
return Integer.compare(o2[1], o1[1]);
}
}
);
for(j=0; j<rowcount; j++)
{
System.out.println(parr[0][j]);
}
Firstly, reading columns in a 2-D Array as 1-D Array is not possible. It can only be done for rows.
As per your code, you are comparing o2[1] and o1[1] which means you are comparing 2nd element in both the rows which is not your requirement.
You better transpose the the matrix and apply the same logic by comparing o2[0] and o1[0] and finally transpose the matrix again to get the desired result..
This gets the job done using selection sort
This only handles two columns. If you want this to handle more columns, you have to used the same idea used to sort the second half.
public static void main(String[] args)
{
// TODO code application logic here
int[][] array2D =
{
{
5, 3, 4, 2, 1
},
{
10, 8, 6, 4, 1
}
};
//One way of printing a 2D array
System.out.print("Before:\n\t");
for (int i = 0; i < array2D[0].length; i++)
{
System.out.print(array2D[0][i] + ", ");
}
System.out.println();
System.out.print("\t");
for (int i = 0; i < array2D[0].length; i++)
{
System.out.print(array2D[1][i] + ", ");
}
System.out.println();
selectionSort(array2D);
//Another way of printing a 2D array.
System.out.print("After:\n\t");
for (int[] item : array2D)
{
for (int entry : item)
{
System.out.print(entry + ", ");
}
System.out.println();
System.out.print("\t");
}
}
//Modified selection sort algrothim
public static void selectionSort(int[][] a1)
{
for (int i = 0; i < a1[0].length; i++)//loop through first half of 2D array
{
int index = i;
for (int j = i + 1; j < a1[0].length; j++)//loop through first half of 2D array
{
if (a1[0][j] < a1[0][index])
{
index = j;
}
}
int smallerNumber = a1[0][index];//Sort the first half like you would a 1D array
int smallerNumber2 = a1[1][index];//When a value will be moved in the first half sort, prepare the number in the same index to be swapped
a1[0][index] = a1[0][i];//swap first half
a1[1][index] = a1[1][i];//swap corresponding number in second half
a1[0][i] = smallerNumber;//complete first half swap
a1[1][i] = smallerNumber2;//complete second half swap
}
}

Loop for printing array values in two columns

I've been trying to make the following for loops to print the original and modified values of an array in two columns, separated by \t\t. Here is my code:
public class Main {
public static void main(String[] args) {
int jay[] = {1,2,3,4,5,6};
System.out.println("Original\tAfter");
for(int y: jay) {
System.out.println(y);
}
multiplyByTen(jay);
for(int z: jay) {
System.out.println("\t"+ z);
}
}
public static void multiplyByTen(int x[]) {
for(int counter = 0; counter<x.length;counter++) {
x[counter] *= 10;
}
}
}
This is the result so far:
Original After
1
2
3
4
5
6
10
20
30
40
50
60
So my question is how to align the value 10 to 1, and 20 to 2 and so on?
This is the solution of your problem, but i don't know if this is exuctly what you want, but it gives you the wished result
public class Main {
public static void main(String[] args){
int jay[] = {1,2,3,4,5,6};
int jay2[] = jay.clone();
multiplyByTen(jay);
for(int i = 0; i < jay.length;i++) {
System.out.println(jay2[i]"\t"+ jay[i]);
}
}
public static void multiplyByTen(int x[]){
for(int counter = 0; counter<x.length;counter++) {
x[counter] *= 10;
}
}
}
This example is from thenewboston java series, I just modified it a bit to see if I can print an original and after arrays side by side.
There is no way to print it side by side with your current construct because array gets manipulated and changed when passed into the method. One of the only ways would be making a copy of the original and print both original and after in the same line.
If your multiplyByTen method accepts a single int value you can do it as:
for(int y : jay)
System.out.println(y + "\t" + mutiplyByTen(y));
If your multiplyByTen method returns an int array, you can do it as:
int[] arr = mutiplyByTen(jay);
for(int x=0; x<jay.length; x++)
System.out.println(jay[x] + "\t" + arr[x]);
But with the current method signature, you need to make another copy of the original array.
My solution using a single array:
public class Main
{
public static void main(String[] args)
{
int jay[] = { 1, 2, 3, 4, 5, 6 };
System.out.println("Original\tAfter");
multiplyByTen(jay);
// To verify values in the original array (you can remove this loop)
for (int z : jay)
{
System.out.println(z);
}
}
public static void multiplyByTen(int x[])
{
for (int counter = 0; counter < x.length; counter++)
{
System.out.print(x[counter] + "\t\t");
x[counter] *= 10;
System.out.println(x[counter]);
}
}
}
OUTPUT
Original After
1 10
2 20
3 30
4 40
5 50
6 60
If you were to use a enhanced loop inside the multiplyByTen(int x[]) method, you would only be changing the local value and not the value in the array. So, if you were to print out the values in the original array, they would remain the same as the original. This way, the values in the array are permanently modified. So, printing the values after the method will show the multiplied values.
Lastly, I would not use print() or println() methods for this. I would use printf() to print out a formatted output. You will find that tabbing will eventually result in misaligned columns (when the number of digits gets larger). You would not run into this issue when using printf().
Keep it simple.
Why not simply do
for(int y : jay) {
System.out.println(y + "\t" + y*10);
}
It is far better to use Arrays.copyOf(...) when you think of using .clone()1:
int jay[] = {1,2,3,4,5,6};
int jay2[] = Arrays.copyOf(jay,jay.length);
System.out.println("Original\tAfter");
multiplyByTen(jay2);
for (int i = 0; i < jay.length; i++) {
System.out.println(jay[i]+"\t\t"+jay2[i]);
}
This way, you print table rows and not columns.
1Why you should never use .clone() for defensive copying.

Not all Array Elements Display When Using A Sort Method Logic

I have this code;
They both use system.out.println statements to print out the array elements. Originally I used a return statement with Arrays.toString(array) to show the array in the main method that worked fine. Now I could like to use print statements just to keep the level of complexity down. As you can see the output form sort is missing the last element in the array, this is because I am using array.length -1. however if I don't use array.length -1 I will get an .ArrayIndexOutOfBoundsException so anyone have a practical solution for this?
import java.util.Arrays;
public class SortMethod
{
static int[] array = {2,1,5,3,5};
public void sort(int[] arrays)
{
for(int i = 0;i < arrays.length - 1;i++ )
{
int store = 0;
if (arrays[i + 1 ] < arrays[i])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i]);
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
SortMethod sort = new SortMethod();
sort.sort(array);
sort.reverse(array);
}
}
Output;
From Sort:1235
From Reverse:55321
First of all your sorting method doesn't actually sort properly. You check values with the value immediately to its left, but what happens if you have a 4 at the end of the list?
{2,1,5,3,5,4}
would return the result:
123545
which is hardly sorted... You'll want to take every value you switch, and check it backwards as well making sure its not also smaller than the previous value. Right now you sort values to the right but never back to the left.
Also you can just do the sorting algorithm, and then iterate through the array afterwards and print the values then, rather than trying to print them in the middle of the sorting method:
public class TestCode
{
static int[] array = {2,1,5,3,5,4,9,1,99,7};
public void sort(int[] arrays)
{
for(int i = 0; i < arrays.length - 1 ;i++ )
{
int store = 0;
// Move larger values to the right
if (arrays[i] > arrays[i + 1])
{
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
// Sort swapped smaller values to the left
for(int j = i; j > 1; j--)
{
if (arrays[j] < arrays[j - 1])
{
store = arrays[j];
arrays[j] = arrays[j - 1];
arrays[j - 1] = store;
}
}
}
}
for(int i = 0; i < array.length; i ++)
{
System.out.print(arrays[i] + " ");
}
System.out.println();
}
public void reverse (int[] arrays)
{
for (int i=arrays.length-1; i >=0; i--)
{
System.out.print(arrays[i] + " ");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
TestCode sort = new TestCode();
sort.sort(array);
sort.reverse(array);
}
}
Gives the output:
1 1 2 3 4 5 5 7 9 99
99 9 7 5 5 4 3 2 1 1
SUMMARY:
When sorting arrays you'll need to iterate though the array array.length - 1 times to compare the values (you don't need to compare the last value with the value to its right because there isn't one).
When printing an array you need to iterate through it array.length times and print out each and every value. Your main problem is coming from trying to print out the array in your sorting algorithm which is only iterating through the array array.length - 1 times when you should probably just print the array outside of the sorting algorithm.
The last line of the public void sort(int[] arrays) function:
System.out.println();
should be
System.out.println(arrays[arrays.length - 1]);
as you want to print the hole array.
And for the record, the public void sort(int[] arrays) function does not actually sort an array. It is not what the sort should do just by one pass of checking and swapping of the neighboring elements.
For example, if the array is initialized as:
static int[] array = {2,1,5,3,5};
The resulting array of sort is: 53215, and the reversed array is 51235. Both are not the intended result.
In sort() you're iterating from 0 to arrays.length-1 (exclusive), so for arrays.length==5 variable i will take values: 0, 1, 2, 3
In reverse() you iterate from arrays.length-1 (inclusive) to 0 - i will take values: 4, 3, 2, 1, 0.
When you remove -1 part from arrays.length-1 in sort() you're getting ArrayOutOfBoundsException because you reference arrays[i + 1] which will be out of arrays range for i==4.
Change your sort method as follows :
public void sort(int[] arrays) {
// int i = 0;
for (int i = 0; i < arrays.length - 1; i++) {
int store = 0;
if (arrays[i + 1] < arrays[i]) {
store = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = store;
}
System.out.print(arrays[i]);
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
}
System.out.println();
}
Just added a new print statement
if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}
to print the last array element.
First of all I would like to point out that the code is incomplete. This is just half the sorting code, I can see you are trying to use bubble sort, but unfortunately the inner loop is missing.
Apart from this there is no problem in this code.
Could you just replace your sort method with the one given below? This will fix all the issues.
public void sort(int[] a){
int temp = 0;
for(int i = 0 ; i < a.length ; i++){
for(int j = 0 ; j< a.length - 1 ; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1]=temp;
}
}
}
printArray(a);
System.out.println();
}
public void printArray(int[] a){
for(int i = 0 ; i < a.length ; i++){
System.out.print(a[i]);
}
}
Also, I would recommend you to read about sorting techniques. You can always visit Sorting articles

Categories

Resources