printing all the array value - java

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.

Related

unable to pass test case for "remove x element after y number of occurrence in array"

I am trying to get pass a coding challenge. The goal is to remove duplicate (after a defined 'n-th' time) from the array.
For example,
int[] arr;
arr = new int[] {1, 2, 2, 3, 3, 3, 4, 5, 5};
arr = tester(arr,1);//return 1,4. anything having more then 1 occurrence is removed from the //array
I have 2 questions here.
I understand that although java is mainly call by value,
more detail: https://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java#:~:text=Longer%20answer%3A,object%20that%20the%20caller%20sees.
and
Is Java "pass-by-reference" or "pass-by-value"?
.
so am I not able to modify/return the value of arr without re-assigning it as I need to use the "new" keyword later on.
example:
I am not able to do the following:
tester(arr,1) //return the original value, as the method has a "new" when converting the
//arraylist into array. There seems to be no work around for this as well..
I am also only passing 2 out of 10 test case in the coding challenge, I am not very sure why. I have also attempted to error handle with string inputs, or length=0 or null, to no success. (or implemented it in hashmap for sake of time complexity)
It does not seem like my logic has an issue, I am just not sure what are the test case as it is hidden.
I believe part of the challenge requires me to return it in the original array, meaning changing the value of arr itself, but i cant find a way to do it without using the new keyword.
Any ideas anyone?
public static int[] tester(int[] data, int n)
{
ArrayList<Integer> storeNon_dup = new ArrayList<Integer>();
//nested for loop to run through the array
//store in arrayList if criteria valid
for(int i = 0; i < data.length; i++)
{
int counter = 0;
for(int j = 0; j< data.length; j++)
{
if(data[i] == data[j])
{
counter++;
}
}
//if not duplicate in n-th occurence, add to list
if(counter<=n)
{
storeNon_dup.add(data[i]);
}
}
//convert arraylist to array
int[] container = new int[storeNon_dup.size()];
for(int i = 0; i<storeNon_dup.size(); i++)
{
container[i] = storeNon_dup.get(i);
}
return container;
}
Alternate solution by using HashMap.
public static List tester(int[] data, int n) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<data.length; i++) {
if(map.containsKey(data[i])) {
map.put(data[i], map.get(data[i])+1);
}else {
map.put(data[i], 1);
}
}
List lst = new ArrayList<Integer>();
for(Integer key : map.keySet()) {
if(map.get(key)<=n) {
lst.add(key);
}
}
return lst;
}

Remove all occurrences of an integer from an int array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I remove all occurrences of an integer, say, 17 in this example from a given array in java?
I tried setting entries to (Integer) null though it doesn't work.
Input array: [0,6,0,17,1,9,17,8,4]
Output array: [0,6,0,1,9,8,4]
for(int i =0;i<ansa.length;i++){
if(ansa[i]==17)
{
ansa[i]=(Integer)null;
}
}
This results in
Exception in thread "main" java.lang.NullPointerException
int[] array = { 0,6,0,17,1,9,17,8,4 };
int[] filtered = Arrays.stream(array).filter(i -> i != 17).toArray();
System.out.println(Arrays.toString(filtered));
:-)
Try this one.
Integer[] array ={0,6,0,17,1,9,17,8,4};
List<Integer> list = new ArrayList<Integer>( Arrays.asList(array ));
list.removeAll(Arrays.asList(17 ));
array =list.toArray(new Integer[0]);
System.out.println(Arrays.toString(array));
I tried setting entries to (Integer) null though it doesn't work.
Of course it doesn't, because the size of the array isn't changed. In order to do this, some of the defined java collections (in particular, the ArrayList and Iterator classes) can provide you of a better approach.
In pseudocode:
Turn array into a List
Iterate over its elements
If the element is the given number
Remove it
Return the List as an Array
You can fill in the blanks, just remember that you can't actually remove an element from an array, because its size is static.
Note: I'm going for the educational approach.
This seems to work - although I suspect people will post better/more efficient solutions.
public void test() {
int[] before = new int[] {0,6,0,17,1,9,17,8,4};
int[] after = remove(before, 17);
System.out.println("Before: "+Arrays.toString(before));
System.out.println("Aftre: "+Arrays.toString(after));
}
private int[] remove(int[] before, int remove) {
// Work out how long it must be.
int keep = 0;
for ( int i = 0; i < before.length; i++ ) {
if(before[i] != remove) {
keep += 1;
}
}
// Make the new one
int[] after = new int[keep];
// Fill it in.
for ( int i = 0, j = 0; i < before.length; i++ ) {
if(before[i] != remove) {
after[j++] = before[i];
}
}
return after;
}
Thats one possible solution:
int[] array1 = new int[]{0,6,0,17,1,9,17,8,4};
ArrayList<Integer> result = new ArrayList<Integer>();
boolean flag = true;
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array1.length; j++) {
if(array1[i]==array1[j]&&i!=j) {
flag = false;
}
}
if(flag) {
result.add(array1[i]);
}
else{
flag = true;
}
}
System.out.println(result);
I think, if you don't want to use an ArrayList, you will have to count how many 17 are in the array and create a new one with ansa.length-count fields
You cannot remove items from an array you are currently using a for loop to cycle through. At the moment you are getting to the end of your array and looking for the next value even though you deleted it. The array length indicator (ansa.length) does not auto update as you are thinking.
You should use List and an iterator to cycle through the list.
You can use then use the .remove function
You are almost done!!
Integer[] ansa = new Integer[] { 0, 6, 0, 17, 1, 9, 17, 8, 4 };
for (int i = 0; i < ansa.length; i++) {
if (ansa[i] == 17) {
ansa[i] = (Integer) null;
}
}
for (Integer integer : ansa) {
System.out.print(integer+","); //0,6,0,null,1,9,null,8,4,
}
You are facing issue, Because you declared primitive I guess like,
int[] ansa = new int[] // Primitive

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

How to compare 2 array without using any methods from the java arrays or collections class?

This is a part of my homework assignment so I need explanation and not just an answer.
I'm creating the legendary purse class. I have to be able to compare one purse(array) to another purse(array). The kicker is that I can't use any methods from the java arrays or collections class. Where do I even start on creating something like this?
An example of what im doing is this:
String[] array1 = {"Quarter", "Dime", "Nickel", "Penny"};
String[] array1 = { "Dime", "Quarter", "Penny", "Nickel"};
(Does Array1==Array2?)
return true/false
Again I need to understand this so please don't just figure it out for me, but throw me some ideas.
The way you'd compare elements between two arrays without Arrays.equal() would be to iterate over each element and compare them one at a time.
String[] array1 = new String[] {"Quarter", "Dime", "Nickel", "Penny"};
String[] array2 = new String[] {"Dime", "Penny", "Quarter", "Nickel"};
public boolean equalArrays(String[] array1, String[] array2) {
if(array1.length != array2.length) {
return false;
}
int matched = 0;
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array2.length; j++) {
if(array2[j].equals(array1[i])) {
matched++;
break;
}
}
}
return matched == array1.length;
}
You could try nested for loops. In pseudo-code:
for each element 'i' in Array1:
for each element 'j' in Array2:
does 'i' equal 'j'?
// do something
else:
// do something else
Does this get you started? Would you like more help?

Why am I getting NullPointerExceptions after assigning references in arrays in a loop?

Why this is not working:
//...
Integer[] array=new Integer[5];
for(Integer x: array){x=-1;}
printArray(array);
//...
// the print function is the following
public static String printArray(Object[] array){
String str="";
for(Object obj : array){
str+=obj.toString()+" ,";
}
System.out.println(str);
}
I got NullPointerException at the for-each statement from the printArray function, why?
Because you never initialized the array with any values, so it just contains a bunch of nulls. You need to give it values before you can call .toString() on them.
For example:
Integer[] array = new Integer[5] { 1, 2, 3, 4, 5 };
Your initial loop (x = -1} is not changing the array, but rather the transient object x in your loop. It would be like doing this:
for (int i = 0; i < array.length; i++) {
Integer j = array[i];
j = -1;
}
Instead, do this if you want to use a loop to initialize:
for (int i = 0; i < array.length; i++) {
array[i] = -1;
}
Integer[] array=new Integer[5];
for(Integer x: array){x=-1;}
The code above doesn't update the array. If you want to update it, you'll need to assign values to the array elements, like this.
for( int i = 0; i < array.length; i++ )
array[ i ] =-1;
The reason the first snippet doesn't do anything useful is that Java is pass by value only. When you create a local variable x and assign an array element to it as its value (as you do in your code), it will contain a reference to the value (the Integer object), but not to the location it's in the array. When you change the value of x, you simply make x point to a different object.
The assignment is done to the local variable x, it is not automatically propagated to the array variable.
Try this:
for(int i = 0; i < array.length; i++) {
array[i] = -1;
}
When you do x=-1, you are assigning a new instance to the variable x and not altering the value of the object in the array. So, your array is effectively uninitialized.
what is going wrong with this java code
Since you asked.... I would
int[] array=new int[5];
Arrays.fill(array);
System.out.println(Arrays.toString(array));
Use int for integer types.
Use the build-in Arrays methods to fill and toString the array.
Use StringBuilder rather than += on a String
Have the printString print a String or printArray print the array OR return a String as you might ignore the result, as you did in your example. Call it toString() or asString() if it returns a String.
Use a varargs on the parameters.
Don't call object.toString() as toString() is called for you. Apart from being shorter, null doesn't thrown an exception!!
Use ", " instead of " ,"
Remove the last " ,".
however say you wanted to write your own printArray ...
// the print function is the following
public static void printArray(Object... objects) {
StringBuilder str = new StringBuilder();
for (Object obj : objects)
str.append(obj).append(", ");
if (str.length() > 1) str.delete(str.length() - 2, str.length());
System.out.println(str);
}
public static void printArray(int... ints) {
StringBuilder str = new StringBuilder();
for (int i : array)
str.append(i).append(", ");
if (str.length() > 1) str.delete(str.length() - 2, str.length());
System.out.println(str);
}
for(Integer x: array){x=-1;} will not initialize the array, it just sets the temp variable x to -1 five times.
Assigning to x doesn't write through to the array. You'll have to do something like this
for(int i = 0; i < array.length; i++) {
array[i] = -1;
}
You never initialized the vales form array.
1.
Integer[] array = new Integer[5];
Here you have reserved space in memory for five Integer objects let say five boxes with an unique addresses;
for(Integer x :array) {
x = -1;
}
Here the things are quite more complicated, what you are actually doing is this
2.1 You allocate memory (another box) for Integer object called x
2.2 You assign (put) value* from table (which is null) to it;
2.3 You assign value -1** to it;
2.4 You repeat from step 2.2 till reserved memory is not finished ( five times).
So the main problem is that you never assign the values into array in other word you are not inserting anything into boxes.
To solve this situation you should allocate to each box a value and then you can use them as you wish.
for(int i=0; i< array.length; i++) {
array[i] = new Integer("-1");
}
Now in each loop we are referring to boxes and there we store the value;
*By value I mean the addresses of those boxes because you are using reference type.
**You also are creating and box in memory and allocate an address for this -1 (that is retrieve from the cache). And in advance the compiler change that x=-1; into x = Integer.valueOf(-1);
Next thing is the method printArray(Object[] array):
You should remember that operations on are very let say expensive because the use a lot of memory. What you are doing there is called concatenation and usually the are not welcome.
The next thing what is wrong is the division of labor You have called the method print array but you are also creating there the string that in fact will be printed. Good approach would be to separate this operations.
public static String arrayToString (Object... array) { //... varags
if(array == null) {
return "null"; //If is null we just return String null.
}
int max = array.length - 1;
if(max == -1) { //We check that array is empty length
return "[]";
}
StringBuilder sb = new StringBuilder("[");
int i = 0;
while(i <= max) {
sb.append(String.valueOf(array[i])); //String.valueOf method is a helper, in situation when in array are null we will get from that method "null" if we wrote array[i].toString; in case when in box i there was no element set we would get null pointer exception. That was your real last problem. But when you are using string builder this is not necessary.
if(i < max) {
sb.append(", ");
}
i++;
}
return sb.append(']').toString();
}
public static String print(String str) {
System.out.println(str);
}
Ps.
For simpler way you could use:
Arrays.fill(array,new Integer(-1));
Arrays.toString(arrays);

Categories

Resources