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
}
}
Related
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
I am trying to find the minimum value in an array by way of creating a new Java class. I am having trouble passing in the array and using it to find the minimum value of an array.
I have a total of two separate arrays that I am trying to find the value of.
Here is the first class I created:
import java.util.*;
public class mooseWeight
{
public int main(String[] args)
{
int[] length1;
int[] length2;
length1 = new int[20];
length2 = new int[50];
//Length 1
System.out.println("Array 1:");
Random rnd = new Random();
for(int i = 0; i<length1.length; i++)
{
length1[i] = rnd.nextInt(400) + 250;
System.out.println(length1[i]);
return length1[i];
}
System.out.println("-----------------------------------");
//Length2
System.out.println("Array 2:");
Random rnd2 = new Random();
for(int j = 0; j < length2.length; j++)
{
length2[j] = rnd2.nextInt(400) + 250;
System.out.println(length2[j]);
return length2[j];
}
}
}
This is currently set up to find the minimum value of length1[] (aka the first array).
This is the class I am trying to pass the arrays into:
public class minWeight
{
public static int getArrayMin(int[] arr)
{
mooseWeight array1[] = new mooseWeight[];
int minValue = array1[0];
for (int i = 0; i < array1.length; i++)
{
if (array1[i] < minValue)
{
minValue = array1[i];
}
//return minValue;
}
return minValue;
System.out.println(minValue);
}
}
My current error:
1 error found:
File: D:\2016-2017\Fall2016\201_CSCE_Programming\Lab 7\minWeight.java [line: 5]
Error: array dimension missing
The error in minWeight not fom the array parameter, it is from this line:
mooseWeight array1[] = new mooseWeight[];
You cannot allocate an array of unknown dimension in java.
Also, your attempt to do so makes no sense.
Just delete the line above from your java method and change the name of the parameter to array1.
Get an IDE like netbeans or eclipse.
Your mooseWeight class contains your main, so when you're creating array1, you're trying to create an array containing your actual program.
mooseWeight array1[] = new mooseWeight[]; is creating an array of mooseWeight objects.
As you don't define a size, this will fail, but even if it didn't, it wouldn't work.
I assume that you meant to create an array of int, then loop over it.
If you created an array of int, then tried to loop over it without adding anything, the loop won't do anything as there's nothing to iterate over.
In your method, you pass in an array of int called arr, so you need to use that to loop over.
If you're trying to pass 2 arrays into the method, creating an array as part of your method still won't work.
You need to modify your method declaration to accept a second array.
Assuming you want to find the smallest value from both of these arrays, I've modified my code snippet to do just that.
If you need to process your second array differently, modify the loop which deals with secondArr.
As mentioned in comments, your mooseWeight class should be named MooseWeight to keep with correct Java naming conventions.
A class name is in PascalCase, with instances in camelCase.
To call the method, use the following snippet.
int[] ar1 = new int[20];
int[] ar2 = new int[50];
//Populate your arrays with values....
int minValue = MinWeight.getArrayMin(ar1, ar2);
Class:
public class MinWeight {
public static int getArrayMin(int[] arr, int[] secondArr) {
int minValue = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] < minValue)
{
minValue = arr[i];
}
}
for (int i = 0; i < secondArr.length; i++) {
if (secondArr[i] < minValue)
{
minValue = secondArr[i];
}
}
System.out.println(minValue);
return minValue;
}
}
As a final concern, in your code, you return minValue before you try to print the result, so the print instruction is always unreachable.
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);
}
}
I have this method that doubles my initial array and then returns it as the new array. When I then reprint the new array, it doesn't show that it doubled. I will paste just the single method, but if it's not enough, let me know. It will print it correctly in the method when I use the second for loop, but when I call the method to print the array, it prints the initial array.
public static int [] doubleArray(int [] p)
{
int [] newArr = new int [p.length * 2];
for (int i = 0; i < p.length; i++)
{
newArr[i] = p[i];
}
p = newArr; //Here I set the new doubled array to equal the array in parameters
for (int i = 0; i < p.length; i++)
{
System.out.print(p[i] + " ");
}
return p;
}
you're populating newArr only through length of p
When you set p = newArr, the array p is still going to keep its size, so its length will not double. You could try to return newArr instead of p, which should give you the doubled array you're looking for.
You are only iterating to p.length. You need to modify your logic to double the length in your first for loop while retaining the correct index to use.
It does doubles the length. Did you want the values to be copied too?
public static int [] doubleArray(int [] p)
{
int [] newArr = new int [p.length * 2];
for (int i = 0; i < p.length; i++)
{
newArr[i] = p[i];
newArr[2*i] = p[i]; //copy the value
}
p = newArr; //Here I set the new doubled array to equal the array in parameters
for (int i = 0; i < p.length; i++)
{
System.out.print(p[i] + " ");
}
return p;
}
length extended.
try this...
public static void main(String[] args) {
int[] a = {1,2,4};
int[] s = doubleArray(a);
System.out.println(Arrays.toString(s));
}
it gives output [1, 2, 4, 0, 0, 0]
Arrays are objects and passed by reference. So if you expect that variable you passed to this method will change it's reference you are wrong.
I ran this code and its produces array of double length and at the beginning there are values of original array. As you use array of primitive type, empty places are populated with default values(0 for int)
Works fine for me. Are you sure you have the right reference for the returned value?
In any case have a look at System.arraycopy
public static void main (final String args[])
{
int [] p = {1,2,3,4,5,6,7,8,9};
final int [] newArr = new int [p.length * 2];
for (int i = 0; i < p.length; i++)
{
newArr[i] = p[i];
}
p = newArr; //Here I set the new doubled array to equal the array in parameters
for (int i = 0; i < p.length; i++)
{
System.out.print(p[i] + " ");
}
}
Ok, #ZouZou solved the issue. When I called the method, I needed to set the initial array to equal the method. Thus when I returned the p array, it wrote it to the initial array.
ie;
initialArray = doubleArray(initialArray);
This works totally fine for me. I guess you have called the method in main like following:
public static void main (final String args[])
{
int [] p = {1,2,3,4,5,6,7,8,9};
doubleArray(p);
for (int i = 0; i < p.length; i++)
{
System.out.print(p[i] + " ");
}
}
In the doubleArray method, you didn't extend the original array. But instead, you return a new one with extended size. So the changes will not reflect to the original array outside of the method.
To get the new one, you should catch the returned array and do printing with the new one.
Is this your actual question? Please clarify!
If yes: normally you can change the original array and make the changes reflects outside the method by changing the return type to void. Those changes could be changing elements' value. But you can't change an array's size once it is declared.
class ArrayApp{
public static void main(final String[] args){
long [] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
for(i=0;i<arr;i++) {
System.out.println(arr[i]);
}
}
}
I get this error,
ArrayApp.java:10: operator < cannot be applied to int,long[]
for(i=0;i<arr;i++) {
^
You need to use the size of the array, which would be arr.length.
for (int i = 0; i < arr.length; ++i)
As of Java 1.5, you can also use the for each loop if you just need access to the array data.
for ( long l : arr )
{
System.out.println(l);
}
arr is an object of long[] , you can't compare int with it.
Try arr.length
Alternatively You should go for
for(long item:arr){
System.out.println(item);
}
You want arr.length
The question has to be seen in the context of a previous question!
From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.
In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):
long[] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2; // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {
System.out.println(arr[i]);
}
Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:
List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
System.out.println(value);
Long arr = new Long[100];
arr[0]=112;
arr[1]=111;
for(int i=0;i<arr.length;i++) {
if (arr[i] != null ) {
System.out.println(arr[i]);
}
}
if you want to show only those which are filled.
You can solve your problem using one line of code:
Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");
See http://java.dzone.com/articles/useful-abuse for more similar tricks.