printing a modified array from a void method - java

I saw the below code in a book. I know that the void method cannot return a value. when I ran the code, the compiler could not print the modified array, while in the book, the values are shown. How can I fix the code to print the modified array?
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println("The values of original array are:");
for(int value: array)
{
System.out.print(value + "\t");
}
modifyArray(array);
System.out.println("The values after modified array are:");
for (int value:array)
{
System.out.print(value + "\t");
}
}
public static void modifyArray(int[] b)
{
for (int counter=0; counter<=b.length; counter++)
{
b[counter] *=2;
}
}

If I am not mistaken, you should be getting an ArrayIndexOutOfBoundsException for your modifyArray() method. change the for loop in the method to
for (int counter=0; counter<b.length; counter++) // use < not <=
{
b[counter] *=2;
}

for (int counter=0; counter<=b.length; counter++)
This code runs for 6 times thus trying to access the 6th element of your array which doesn't exist. It must be ArrayIndexOutOfBoundsException error.
Change above line to:
for(int counter = 0; counter<b.length; counter++)
This will work!

The code actually works but there is an error in the method for loop that cause a IndexOutOfBound Exception this is the correct version.
public static void modifyArray(int[] b)
{
for (int counter=0; counter<b.length; counter++)
{
b[counter] *=2;
}
}
The method returns void but you can read the modify values inside the array because you are passing as method argument the reference of the array not a copy of the array. this is a very basic concept of the Java Language you should start reading
Passing Information to a Method or a Constructor.

Related

index out of range error in java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am trying to find the max value of a 2D array in java.
import java.util.*;
public class ikiBoyutlu {
public static void ikiBoyut(int[][]a){
int eb= a[0][0];
for(int i=0;i<a.length;i++){
for(int j=0; j<(a[0].length);j++){
if(a[i][j]>eb){
eb=a[i][j];
}
}
}
System.out.println("The max value of array= "+ eb);
}
public static void main(String[] args){
int a[][] ={{2,5,7,0,-6,28,43},{-96,45,3,21}};
ikiBoyut(a);
}
}
But I get index out of range error. I wonder why?
Thanks!
You're iterating over different nested arrays, while invariably watching i < a[0].
Your inner loop should be declared this way, instead:
for(int j=0; j<(a[i].length);j++)
and in your example the second inner array is smaller than the first. so when iterating through the second with the length of the first, it will definitely get out of the bounds ...
You have a two dimensional array, which is basically an array of arrays.
Your two two dimensional array effectively contains two arrays with different lengths.
Your second loop has the condition of
j<(a[0].length)
when it should be
j<(a[i].length)
Use the length of each array element.
You are testing the inner loop against a[0].length which is the length of the first array in your jagged multidimensional array (and longer than the second). Instead, use a[i].length - and you might also initialize eb with Integer.MIN_VALUE and use Math.max(int, int) instead of coding your own test. Like,
public static void ikiBoyut(int[][] a) {
int eb = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
eb = Math.max(eb, a[i][j]);
}
}
System.out.println("The max value of array= " + eb);
}
This is also a place where you could potentially eliminate errors by using a for-each loop. For example,
public static void ikiBoyut(int[][] a) {
int eb = Integer.MIN_VALUE;
for (int[] arr : a) {
for (int i : arr) {
eb = Math.max(eb, i);
}
}
System.out.println("The max value of array= " + eb);
}
And, in Java 8+, we can use lambdas to shorten it significantly. Like,
public static void ikiBoyut(int[][] a) {
int eb = Stream.of(a).flatMapToInt(IntStream::of).max().orElse(Integer.MIN_VALUE);
System.out.println("The max value of array= " + eb);
}

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.

Array shifting...showing test case after Run [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I want to shift elements in an array to the right by 1. The last element should go to position 0. So far, I only have the shifting to the right part done, I want to see if this is the right but when I press run, nothing shows up in the console. I know I have to put System.out.println(); in the main but I don't know what to call with the print command. Here is my code.
I tried putting in System.out.println(rotate({1,2,3,4})); into main but I get an error...
public class Rotate {
static void rotate(int[] A) {
int arrayLength = A.length;
for(int i = 0; i <= arrayLength-1; i++){
A[i] = A[i+1];
}
}
public static void main(String[] args){
}
}
You need to make a call to a function that can print, for example System.out.println(). Now there are some other issues with your code and you'll need to make some changes (there is more than one way to do this). One way would be to return an array from your rotate function, and then print the arrays that is returned.
static int[] rotate(int[] A) {
int arrayLength = A.length;
for(int i = 0; i <= arrayLength-1; i++){
A[i] = A[i+1];
}
return A;
}
We can call this now from our main method, and print each element. If you just call the System.out.println()method and pass it an array, it will print the Hashcodefor this object. This is not that usefull for printing information of an array. So instead, you can write a loop and print each element in the array.
public static void main (String[] args)
{
int[] x = {1,2,3,4};
int[] y = (rotate(x));
System.out.println(y) // prints the hash, not what you want..
for(int i = 0; i < y.length(); i++){
System.out.println(y[i]);
}
}
Instead of printing each element of the array seperately, you could also print the entire array using System.out.println(Arrays.toString(y));.
You'll still get an error now
This is because your rotate method is not implemented correctly. But that is beyond the scope of this question I suppose.
To verify that this is actually working, you could try to print the array before applying rotateto it.
int[] x = {1,2,3,4};
for(int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
// or alternative
System.out.println(Arrays.toString(x));
To solve rotate and print problem (and if you don't want to return array):
static void rotate(int[] A) {
int arrayLength = A.length;
int t = A[arrayLength-1];
for (int i = arrayLength - 1; i > 0; i--) {
A[i] = A[i-1];
}
A[0] = t;
for (int i : A) {
System.out.println(i);
}
}

exception when trying to print an array in Java

I have this very little program in Java (just started to learn this language):
package hellojava;
public class Hellojava {
public static void main(String[] args) {
System.out.println("Hello World");
int[] nums = {1,2,3,4,5,6,7,8,9,10};
int[] revs = reverse(nums);
for (int i : revs) {
System.out.println(revs[i]);
}
}
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i=0, j=result.length-1; i<list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
}
It throws this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at hellojava.Hellojava.main(Hellojava.java:9).
So I pretty know what's wrong and know how to fix it, but my question is about that for loop. I thought that this enhanced for loop will work here, but it doesn't. Why's that?
The problem is that the enhanced for loop gives the values of the array, not the indexes. So, 10 the value is returned, which is an invalid index.
Your loop beginning:
for (int i : revs) {
is equivalent to
for (int index = 0; index < revs.length; index++)
{
int i = revs[index];
}
The enhanced for loop gives you the values in an array, not the indexes. Try
for (int i : revs) {
System.out.println(i);
}
Simple:
for (int i : revs) {
System.out.println(i);
}
You are using a foreach statement instead of a for indexed loop. The foreach loop iterates the array for you and assign the element of the array to i so don't consider it as an index of an array.
Here is an Oracle documentation on the For-Each Loop.
Replace
System.out.println(revs[i]);
with
System.out.println(i);
Explanation: The variable i is the integer element and not an index.

Using a for loop to copy one array to another

I've been working with arrays and I'm trying to find a way to copy one array to another solely with a for loop (I've seen things like arrayCopy and clone in other threads, but for this exercise I need to just copy from one array to another using a for loop).
Right now my code executes, but just spits this out: "[D#133c5982". The code I'm using is:
public class sorted
{
public static void main(String[] args)
{
int [] unSortedArray = {8,12,6,5,19};
System.out.println(copyArray(unSortedArray));
//System.out.println(sortedArray(unSortedArray));
}
public static int[] copyArray(int[] array)
{
int [] copyArray;
copyArray = new int[array.length];
for (int i = 1; i < array.length; i++)
{
copyArray[i] = array[i];
}
return copyArray;
}
First of all, you are not copying whole array, as you starting your index with 1
as in your code
for (int i = 1; i < array.length; i++)
{
copyArray[i] = array[i];
}
start the index with 0
and second you can make use of Arrays.deepToString(array) or Arrays.toString(array) to print array in readable format
Your code is OK, it does copy the array. When you do System.out.println it prints out the default implementation of the array's toString() method). To see that it is indeed copied, you can do
for (int i = 0; i<unsortedArray.length; i++) {
System.out.println(unsortedArray[i]);
}
for (int i = 0; i<copiedArray.length; i++) {
System.out.println(copiedArray[i]);
}
EDIT: see the comments for what you code actually prints out
copyArray returns an array and that's what you are printing. What you see is the Java Virtual Machine way of representing objects as strings. #12345 is the object's ID.
There is nothing wrong with the code provided, except a } at the end (possibly omitted while copying).
When printing you are using the arrays default toString which doesn't print the content of the Strings.
Since Java 1.5 you can use Arrays.toString(array) to get a nice String representation of the array.
See the API here.
Use this with System.out.println to get a nice printout.
What you have done is correct. But if you print an array using System.out.println(copyArray(unSortedArray)); it only prints out the location of the array. Instead, try printing each element of the array in a for loop.
for (int i = 1; i < array.length; i++)
{
system.out.println(array[i]);
}
//Arrays.toString(<arrayname>) can also be used in place of the for loop.
Also, array index starts at 0. So, your method should be as follows.
public static int[] copyArray(int[] array)
{
int [] copyArray;
copyArray = new int[array.length];
for (int i = 0; i < array.length; i++)
{
copyArray[i] = array[i];
}
return copyArray;
try this
package naveed.workingfiles;
import java.util.Arrays;
public class Array
{
public static void main(String[] args)
{
int [] unSortedArray = {8,12,6,5,19};
int [] unSortedCopyArray =new int [unSortedArray.length];
//System.out.println(sortedArray(unSortedArray));
for(int i=0;i<unSortedArray.length;i++)
{
unSortedCopyArray[i]=unSortedArray[i];
}
System.out.println(Arrays.toString(unSortedArray));//exist array
System.out.println(Arrays.toString(unSortedCopyArray));//copied array
}
}

Categories

Resources