How to initialize values in a local array? [duplicate] - java

This question already has answers here:
How to initialize an array in Java?
(11 answers)
Closed 5 years ago.
I'm running into a little trouble understanding how I can initialize an array with the values that are listed in the notes. How would I be able to set up array and proceed to use the code below to properly return the respective output.
This question varies from the duplicate linked because it is asking how to initialize the array within a local method.
/*Write a method that reverses the sequence of elements in an array. For example, if
you call the method with the array
1 4 9 16 9 7 4 9 11
then the array is changed to
11 9 4 7 9 16 9 4 1*/
public static void reverse(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}

First you need to define an array and to initialize it with the given values. This could be done directly on the declaration of the variable. Then you need to pass the reference to the reverse method.
public static void main(String[] args) {
int[] array = {1, 4, 9, 16, 9, 7, 4, 9, 11};
reverse(array);
Arrays
.stream(array)
.forEach(System.out::println);
}
private static void reverse(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
You can find more information about how to initialize an array here:
http://www.baeldung.com/java-initialize-array

Related

Array elements dissapearing during a for loop [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 months ago.
This post was edited and submitted for review 3 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I'm not new at Java, but I'm in JUnit. I'm having a problem with a simple for loop. I'm ordering array elements with bubble sorting, but I don't know why the two last elements disappear during the loop. I know it will be a little tiny thing, but I can't find the mistake. Could you help me, please?
This is my class:
package exercise5;
public class Ejercicio5 {
public static int[] sort(int[] arrayNums) {
// array that I have tried: {6,5,8,3,7,1}; [6]
System.out.println("size: " + arrayNums.length);
for (int j = 0; j < arrayNums.length; j++) {
System.out.println("j:" + j);
if (arrayNums[j] > arrayNums[j + 1]) {
System.out.println("entra");
int numGuardado = arrayNums[j + 1];
arrayNums[j + 1] = arrayNums[j];
arrayNums[j] = numGuardado;
}
print(arrayNums);
}
return arrayNums;
}
public static void print(int[] arrayParaImprimir) {
System.out.println("Array:");
for (int j = 0; j < arrayParaImprimir.length; j++) {
if (j != arrayParaImprimir.length - 1) {
System.out.print(arrayParaImprimir[j] + ", ");
} else {
System.out.print(arrayParaImprimir[j] + "\n");
}
}
}
}
My TestClass with JUnit5:
package exercise5;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import junit.framework.TestCase;
public class Ejercicio5Test extends TestCase{
#Test
public void resultadoCorrecto(){
int[] correct = {1,3,5,6,7,8};
int[] array = {6,5,8,3,7,1};
int[] result = Ejercicio5.sort(array);
Assert.assertArrayEquals(result, correct);
}
#Test
public void resultadoIncorrecto(){
int[] correct = {1,3,5,6};
int[] array = {3,5,6,1};
int[] result = Ejercicio5.sort(array);
Assert.assertArrayEquals(result, correct);
}
}
When j is equal to 4, the ordering is doing: 5, 6, 3, 7, 1, 8
but when j passed to 5, two elements disappear.
In addition, in my Test class there are only two methods, but, when I run it, it recognises one more and give me an error:
This is the array that I have tried {1,3,5,6,7,8} and this is that I expected {5,6,3,7,1,8} with 6 of array's size, not element disappearing.
enter image description here
This is the output in console. NOT ArrayIndexOutOfBounds. Only disappear 2 elements, and the size changes, not throwing any exceptions:
size: 6
j:0
entra
Array:
5, 6, 8, 3, 7, 1
j:1
Array:
5, 6, 8, 3, 7, 1
j:2
entra
Array:
5, 6, 3, 8, 7, 1
j:3
entra
Array:
5, 6, 3, 7, 8, 1
j:4
entra
Array:
5, 6, 3, 7, 1, 8
j:5
size: 4
j:0
Array:
3, 5, 6, 1
j:1
Array:
3, 5, 6, 1
j:2
entra
Array:
3, 5, 1, 6
j:3
for (int j = 0; j < arrayNums.length; j++) {
This loops for every number in the input. Then you..
if (arrayNums[j] > arrayNums[j + 1]) {
Compare this to the next number in the input. On the last loop, you are therefore comparing the last number (arrayNums[j]) with the.. number after that. Which doesn't exist, hence, ArrayIndexOutOfBoundsEx.
You want to loop one fewer.
You missed one loop here is the correct code -
public class Ejercicio5 {
//you don't need to return as it modifies exiting array
public static void sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap arr[j+1] and arr[j]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
/* Prints the array */
public static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
int[] array = {6,5,8,3,7,1};
Ejercicio5.sort(array);
System.out.println("Sorted array");
Ejercicio5.printArray(array);
}
}
output - Sorted array 1 3 5 6 7 8
and your testcases should work now with minor changes
If you run the JUnit test, it runs all the methods annotated by #Test.
Your output exactly reflects the 2 calls of your sort function, first from resultadoCorrecto() to line "j:5", second call from resultadoIncorrecto(), what outputs lines after that (from "size: 4").
So nothing has disappeared.
resultadoCorrecto() calls sort function with an array size of 6.
resultadoIncorrecto() calls sort function with an array size of 4.
Your bubble sort problem:
The for loop must go until index < length-1.
You must bubbling up all the bubbles with another for cycle around. (See Sagar Kale's answer.)

an int array from Command Line Arguments

I'm trying to convert command line arguments in an int array, but it appears a "0" in the end of the array. How can I fix it?
import java.util.Arrays;
public static void main(String[] args){
int[] game = new int[9];
for (int i = 0; i <= 8; i++)
game[i] = Integer.parseInt(args[i]);
System.out.println(Arrays.toString(game));
}
Example run:
$ java edu.kit.informatik.TicTacToe 5 6 4 1 2 3 7 8 9
[5, 6, 4, 1, 2, 3, 7, 8, 9, 0]
I have tested your code, there aren't '0' at the end of the list. I recommend you that use args.length for handling variety arguments count.
public static void main(String[] args) {
int[] game = new int[args.length];
for (int i = 0; i < args.length; i++)
game[i] = Integer.parseInt(args[i]);
System.out.println(Arrays.toString(game));
}
When you create a new int[] array in Java, its initial contents are all zeros. If you then fill it up with fewer numbers than it is long, you'll see the zeros that have not been overwritten at the end.
// creating an array of size 10
int[] array = new int[10];
// only filling up the first 8 elements
for (int i = 1; i <= 8; i++) {
array[i-1] = i;
}
// printing the full array
for (int i = 0; i < array.length; i++) {
System.out.print(i + " ");
}
System.out.println();
This will output:
1 2 3 4 5 6 7 8 0 0
The last two zeros are just the elements that have not been set to anything else.

How to pass by value in java? [duplicate]

This question already has answers here:
Problem with assigning an array to other array in Java
(4 answers)
Make copy of an array
(11 answers)
Closed 2 years ago.
I'm trying to make a project in which an array is sorted by different sorting algorithms. However, I have noticed that after one algorithm sorts the array and displays the value, the original array is also changed. How can I solve this?
public static void main(String[] args) {
int[] array = {20, 35, -15, 7, 55, 1, -2};
printArray(array);
boubleSort(array);
printArray(array);
}
The first function prints out the array in its unsorted form, the second one sorts the array and then prints the sorted array. The third line prints the original array (which should remain unsorted) as sorted. Why odes this occur and how can I change this?
public static void boubleSort(int[] array) {
System.out.println("Bouble Sort");
int [] arr = array;
for(int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
for (int i = 0; i < lastUnsortedIndex;i++) {
if(arr[i] < arr[i+1]) {
swap(arr,i, i+1);
}
}
}
printArray(arr);
}
public static void swap(int [] array, int i, int j) {
if (i == j) {
return;
}
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void printArray(int [] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println();
}
Current output: Desired output:
20 20
35 35
-15 -14
7 7
55 55
1 1
-2 -2
Bouble Sort
35 35
20 20
7 7
1 1
-2 -2
-15 -15
20 20
35 35
-15 -14
7 7
55 55
1 1
-2 -2

How to create a sum of alternating integers from an int array? [duplicate]

This question already has answers here:
How to write a program that reads a sequence of integers into an array and that computes the alternating sum of all elements in the array?
(5 answers)
Closed 6 years ago.
I am supposed to compute the alternating sum of all elements in an array. For example, the array with values 1 4 9 16 9 7 4 9 11 should compute
1 - 4 + 9 - 16 + 9 - 7 + 4 - 9 + 11 = -2
following code was provided by instructor
public static void main(String[] args)
{
double[] data = { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
AlternatingSum util = new AlternatingSum();
double total = util.alternatingSum(data);
System.out.println("Expected sum: -2");
System.out.println("Alternating sum: " + total);
}
What does util.alternatingSum(data) mean? Do I have to create an alternatingSum method? And if so, what is the heading code for that method?
Thank you for any help.
What does util.alternatingSum(data) mean?
It calls alternatingSum(double[]) method of AlternatingSum class. util is an object of AlternatingSum class, which is used to call this method.
Do I have to create an alternatingSum method?
If the code is not there, this code will not compile!
You need to have an AlternatingSum class, inside which you'd have an alternatingSum() method.
So, YES, you need to have that code for this code to compile and execute successfully.
And if so, what is the heading code for that method?
The method header should go as:
double alternatingSum(double[])
{
// your code goes here.
}
as this method accepts an array of doubles, and returns a double value.
Here is your method,
public double alternatingSum(double in) {
double alternatingSum = in;
if(data != null || dataSize > 0) {
for(int i = 0; i < dataSize; i = i + 2) {
alternatingSum += data[i];
}
for(int i = 1; i < dataSize; i = i + 2) {
alternatingSum -= data[i];
}
}
return alternatingSum;
}
I found it here
Here's an example using Java 8 streams:
double[] data = { 1, 4, 9, 16, 9, 7, 4, 9, 11 };
double result = IntStream.range(0, data.length)
.mapToDouble(i -> i)
.map(i -> i % 2 == 0 ? data[(int)i] : data[(int)i]*-1)
.sum();
System.out.println(result);

Arraylist OutOfBoundsException: Index: 5, Size: 4 [duplicate]

This question already has answers here:
ArrayIndexOutOfBounds on enhanced for loop
(2 answers)
Closed 6 years ago.
I'm going through an example on Code Wars. Essentially, taking a number, finding the multiples of 3 and 5 and adding these together. Assuming the number is 10, we'll have 3,5,6,9.
I am at the point where I want to add the multiples together (the foreach loop at the bottom) but I keep getting an OutOfBoundsException. I don't understand how it is reaching index 5! Can someone please explain this to me?
I've seen a few examples of this error on here but can't checking through these I've not been able to resolve the issue, sorry.
package Test;
import java.util.ArrayList;
import java.util.List;
public class MultiplesOf3And5 {
public static void main(String[] args) {
int number = 10;
int total = 0;
List<Integer> multiples = new ArrayList<Integer>();
for (int i = 1; i < number; i++) {
if (i % 3 == 0) {
System.out.println(i + " is a multiple of 3");
multiples.add(i);
} else if (i % 5 == 0) {
System.out.println(i + " is a multiple of 5");
multiples.add(i);
}
}
for (int j : multiples){
System.out.println(multiples.get(j));
System.out.println(multiples.toString());
total += multiples.get(j);
}
System.out.println(total);
}
}
for-each loop iterates the values of your List multiples, you used each value of the List as index by accident. Fix it as below:
for (int j : multiples){
System.out.println(j);
System.out.println(multiples.toString());
total += j;
}
The output is:
3 is a multiple of 3
5 is a multiple of 5
6 is a multiple of 3
9 is a multiple of 3
3
[3, 5, 6, 9]
5
[3, 5, 6, 9]
6
[3, 5, 6, 9]
9
[3, 5, 6, 9]
23
System.out.println(j);
You are trying to get the jth object out of the list, but the you are iterating over the values not the index.
your ArrayList have = 3,6,9(factor of 3) & 5(factor of 5)
so total 4-value reside into ArrayList.
now you are trying to get value from ArrayList not based upon index like 0,1,2,3...
but you are fetching value from ArryList likewise, multiples.get(3), .get(6)... etc.
that's why you get error, like ArrayIndexOutOfBoundException.
Better to follow this way,
for (int j : multiples){
System.out.println(j);
System.out.println(multiples.toString()); // not required but you want then remain it is likewise... or else remove this line
total += j;
}
Your error is occurring because your for loop is assigning the actual values of your array list. Try this:
for(int j = 0, j < multiples.size(), j++) {
System.out.println(multiples.get(j))
}
The var j holds the current value of your iteration, not the current index of the iteration.
This should be enough :
for (int j : multiples) {
System.out.println(multiples.toString());
total += j;
}

Categories