Array printing weird character [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
I'm trying to create a program that removes a given character from an array and then prints out the new array and whenever I print it out I get weird results like [I#120acab
public static int[] removeVal(int[] numArray, int val)
{
int purge = 0;
int keep = 1;
int arrayVal = 0;
for (int item : numArray)
{
if(item == val)
purge = purge + 1;
else
keep = keep + 1;
}
int[] newArray = new int[keep];
for (int taco : numArray)
{
if(taco != val)
newArray[arrayVal] = taco;
arrayVal = arrayVal + 1;
}
return newArray;
}

You should use Arrays.toString to print the array. This will show the individual elements of the array.
The default toString implementation of Object class returns what you see.

Related

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

Removing every 2nd element in array list [duplicate]

This question already has answers here:
Calling remove in foreach loop in Java [duplicate]
(11 answers)
Closed 4 years ago.
I've been trying so far to write a method ,removeEvenLength that takes an ArrayList of Strings as a parameter and that removes all of the strings of even length from the list. But so far I've been getting a IndexOutOfBoundsException and I don't know why.
Any help would be appreciated
public static ArrayList<String> removeEvenLength(ArrayList<String> list) {
int size = list.size();
ArrayList<String> newLst = new ArrayList<String>();
for (int x = 0; x < size; x++) {
if (list.get(x).length() % 2 == 0) {
list.remove(x);
}
}
return list;
}
Once you remove an element, the size of the list reduces by one and hence the variable size no longer denotes the true size of the list
Also, after you remove a String at index i, the elements from i+1, i+2.. list.size() - 1 will be moved to the left by one position. So, incrementing the loop counter x all the time is wrong and you will skip some elements.
Here's a way to do it right
for (int x = 0; x < list.size();) {
if (list.get(x).length() % 2 == 0) {
list.remove(x);
} else {
x++;
}
}
public static List<String> removeEvenLength(List<String> list) {
List<String> newList = new ArrayList<String>();
for (String item: list) {
if (item.length % 2 != 0) {
newList.add(item);
}
}
return newList;
}

Assign more than one variable to a method [duplicate]

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Initializing multiple variables to the same value in Java
(7 answers)
Closed 5 years ago.
I am trying to assign 3 integer arrays to a method that returns one version. But when i try this it says variable bubbleArray and variable insertionArray have not been initialized. Is there another way to do this and still keep the same original values from the method.
Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();
bubbleSort(radioValue,bubbleArray);
selectionSort(radioValue,selectionArray);
insertionSort(radioValue,insertionArray);
public Integer[] numGenerator() {
Random rn = new Random();
originalOutput.setText("");
sortedOutput.setText("");
referenceArray.clear();
if (number10Button.isSelected()) {
for (int i = 0; i < 10; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number100Button.isSelected()) {
for (int i = 0; i < 100; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number1000Button.isSelected()) {
for (int i = 0; i < 1000; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
} else if (number5000Button.isSelected()) {
for (int i = 0; i < 5000; i++) {
int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
referenceArray.add(answer);
originalOutput.append(referenceArray.get(i).toString() + "\n");
}
}
Integer[] bubbleArray = referenceArray.toArray(new Integer[referenceArray.size()]);
return bubbleArray;
}
Your code declares 3 Integer[] variables and assigns the last one to what numGenerator() returns.
Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();
Now since you want three arrays, not just three variables pointing to one array you need to make copies of the array, for example with clone(). If you don't make copies you will have one array which is sorted by bubble sort and the other sorting methods will try to sort an already sorted array, which is not what you want.
Integer[] bubbleArray = numGenerator();
Integer[] insertionArray = bubbleArray.clone();
Integer[] selectionArray = bubbleArray.clone();

How to check whether a number there in integer variable? [duplicate]

This question already has answers here:
checking an integer to see if it contains a zero
(7 answers)
Closed 7 years ago.
For example, we can find what we search in an array as below:
int values [] = {3, 5, 7};
for(int i = 0; i < values.length; i++)
{
if(values[i] == 3)
{
System.out.println("3 is in array.\n");
}
}
but what would happen if we search a number in integer value? Can we find what we search in that variable? I tried something with for each loop but it hasn't worked. Does Java provide this process?
int value = 151;
for(int found: value)
{
if(found == 3)
{
System.out.println("3 is in array.\n");
}
}
You could simply use String.contains():
if (Integer.toString(value).contains("3")) { ... }
I know this is not a neat way of doing it, nevertheless it is one of the ways to do it.
Steps involved:
1) Convert it to String.
2) Look for a particular character in that string using String's built in contains(CharSequence s) method
int value = 151;
//First Step:
String numberAsString = Integer.toString(value);
//Second Step:
if (numberAsString.contains('3')){
System.out.println("Found 3");
}
And remember variable value is not lost. You can use/reuse it.

How should I concatenate arrays [duplicate]

This question already has answers here:
How can I concatenate two arrays in Java?
(66 answers)
Closed 7 years ago.
I am using a function that returns some integers
int[] return;
This function is inside a loop like this
public static int[] toEOBArray(double[] tempVal)
{
int[] out;
for (int i = 0; i < 10; i++)
{
out = fixArray(tempVal[i]);
}
return out;
}
What I want is as new arrays come from fixArray to add them to the previous results, so in the end I have a big array that will contain all the small arrays resulting from fixArray
What is the most efficient way of doing this?
My main problem is not knowing how to initialize the array that is to hold all the values.
If you want to work only with arrays, you must first find the length of the concatenated array. Then you can use System.arraycopy to copy the small arrays to the output array.
public static int[] toEOBArray(double[] in)
{
int[][] arrays = new int[10][];
int len = 0;
for (int i = 0; i < 10; i++)
{
arrays[i] = fixArray(tempVal[i]);
len += arrays[i].length;
}
int[] out = new int[len];
int offset = 0;
for (int i = 0; i < 10; i++)
{
System.arraycopy(arrays[i],0,out,offset,arrays[i].length);
offset += arrays[i].length;
}
return out;
}
If you insist on working with native arrays (as opposed to a Collection like ArrayList) then you will want to use ArrayUtils class from Apache Common Lang that adds many Collection-like features to Java native arrays, one of which is addAll:
ArrayUtils.addAll(fixArray, tempVal);

Categories

Resources