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

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);
}
}

Related

Arrays and For-loop - Incorrect output while printing Random elements

I am pretty new in this world, and I must say sometimes things that looks easy are pretty harsh.
I am stuck with a task that entails dealing with an array and for-loops.
I should iterate over the array and for every iteration step print a different random string. My current code is not working correctly, the only thing I'm getting a random item and the same index printed multiple times.
My output right now:
relax
2
2
2
2
How can I fix that and get a correct randomized output?
My code:
public static void main(String[] args) {
int i;
String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
java.util.Random randomGenerator = new java.util.Random();
int x = Cofee.length;
int y = randomGenerator.nextInt(x);
String frase = Cofee[y] ;
System.out.println(frase);
for(i = 0; i < Cofee.length; i++)
System.out.println(y);
}
You assign a value to y once, and you print y repeatedly. The value of y doesn't change. To do that, you would need to call randomGenerator.nextInt(x) for each iteration of the loop!
However, if you want to randomize and print the array, use:
public static void main(String[] args)
{
String[] coffee = {"pick it","drink it","relax","put it in a cup",};
// this wraps the array,
// so modifications to the list are also applied to the array
List<String> coffeeList = Arrays.asList(coffee);
Collections.shuffle(coffeeList);
for(String value : coffee)
System.out.println(value);
}
As an aside, don't use String coffee[], but use String[] coffee. Although Java allows putting the array type after the variable name, it is considered bad form.
Or use a list directly:
public static void main(String[] args)
{
List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
Collections.shuffle(coffeeList);
for(String value : coffeeList)
System.out.println(value);
}
For that, you can implement a shuffling algorithm.
It's not so scaring as it might sound at first. One of the famous classic shuffling algorithms, Fisher–Yates shuffle is relatively easy to grasp.
The core idea: iterate over the given array from 0 to the very last index, and for each index swap the element that corresponds to the randomly generated index between 0 and the current index (i) with the element under the current index.
Also, I would advise creating a separate array representing indices and shuffle it in order to preserve the array of string its initial state (you can omit this part and change the code accordingly if you don't need this).
That's how it might be implemented:
public static final Random RANDOM = new Random(); // we need an instance for random to generate indices
A Fisher–Yates shuffle implementation:
public static void shuffle(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
swap(arr, i, j); // swapping elements `i` and `j`
}
}
Helper-method for swapping elements:
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Usage-example:
String[] coffee = {"pick it","drink it","relax","put it in a cup"};
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
shuffle(indices);
for (int i = 0; i < coffee.length; i++) {
String next = coffee[indices[i]];
System.out.println(next);
}
Output:
drink it
pick it
put it in a cup
relax

Reverse Print Given Array [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
import java.util.*;
class Example{
public static int[] reverse(int[]ar){
for (int i = 0; i < (ar.length); i++)
{
ar[i]=ar[(ar.length-i-1)];
}
return ar;
}
public static void main(String args[]){
int[] xr={10,20,30,40,50};
System.out.println(Arrays.toString(xr));
int[]y=xr;
int[]z=reverse(xr);
System.out.println(Arrays.toString(z));
}
}
This code output get: [50,40,30,40,50].
But I want to print the reverse of the given Array.
And I want to know how this output([50,40,30,40,50]) generated
When i=0
ar[i]=ar[(ar.length-i-1)]
assigns the last element of the array to the first index of the array. Thus the original first element of the array is overwritten before you have a chance to assign it to the last index.
This happens for all the indices of the first half of the array.
If you want to reverse the array in place, you need some temp variable, and you should make a swap in each iteration:
public static int[] reverse(int[]ar)
{
for (int i = 0; i < ar.length / 2; i++) {
int temp = ar[i];
ar[i] = ar[(ar.length-i-1)];
ar[(ar.length-i-1)] = temp;
}
return ar;
}

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);
}

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
}
}

I keep receiving a .class expected error [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 2 years ago.
Here is what I'm supposed to do:
Write a program to read a 2-D array of 4x4. Then read the first element of the array and compare it with the third element of each column. Replace the smaller value with the larger values of the two. Create a method called swap to swap the values.
I'm not sure what I'm doing wrong and I'm just starting to learn arrays. My teacher is very conceptual and isn't very concrete on his definition so I'm having trouble with it. I keep receiving a .class expected error.
public class Array {
public static void main(String[] args) {
int num [][] = {{4, 6, 7, 2},
{5, 12, 9, 8},
{1, 0, 3, 10},
{5, 3, 14, 11}};
System.out.println("the array elements are:");
for(int i = 0; i < num.length; i++){
System.out.println();
for(int j = 0; j < num[i].length; j++)
System.out.print(num[i][j] + " ");
}
System.out.println("swaped elements are:");
for(int i = 0; i < num.length; i++){
System.out.println();
for(int j = 0; j < num[i].length; j++)
System.out.print(swap(num[][]) + " ");
}
}
public static void swap (int x[][]){
for(int i = 0; i < x.length; i++){
int temp = x[0][i];
if (x[0][i] > x[2][i] ){
x[2][i] = temp;
x[0][i] = x[2][i];
}
}
}
}
swap() doesn't return anything. Even if you did resolve the other issue (num[][] is a syntax error), you'd need to specify something to return from swap. Hint: probably the array you modified.
Write a program to read a 2-D array of 4x4.
I don't see you reading something. Just initializing it. Maybe you should read from stdin or from a file?
Then read the first element of the array and compare it with the third element of each column.
Replace the smaller value with the larger values of the two.
Create a method called swap to swap the values
As a swap method I would expect a method with 4 indexes for the 2 positions in the 2D-Array, where the values to swap are located.
public static void swap (int x[][], int i1, int i2, int j1, int j2) {
int temp = x[i1][j1];
x[i1][j1] = x[i2][j2];
x[i2][j2] = temp;
}
Have you heard about the simplified for-loop?
public static void show (int x[][]) {
for (int [] inner : x)
for (int i : inner)
System.out.print (i + " ");
}

Categories

Resources