Removing element from array error - java

In the following code, if the size of the array is larger than 20, I'm trying to remove anything after 20 from the array. In my loop, I have userinput.remove(20 + i); However, I'm getting that it can't find the symbol remove? I'm not sure why it's doing this if the error.add itself is actually working.
userinput is defined earlier in the code
public static void checknames(String[] userinput){
ArrayList<String> error = new ArrayList<String> ();
if(userinput.length > 20){
for(int i=0; i<userinput.length - 20; i++){
error.add(userinput[20 + i]);
userinput.remove(20 + i);}
JOptionPane.showMessageDialog(null, "You can only enter up to 20
employees. \n The following employees exceed this limit." + error);
}
}

The error is correct - there is no such remove method for arrays. You should either:
Use a List instead, like the ArrayList you have used for error.
Create a new array which is 1 element shorter, and copy over everything except the element you are trying to remove.

You cannot call remove an array. You can't change the size of the array. But you could set that element to null:
userinput[20 + i] = null;

userinput.remove(20 + i);
userinput is array of String[]. There is not method remove(..) available for array.
May be you need to set value to null for indexes greater than 20 (or) create a new String array with only first 20 elements and discard userinput.

Try this:
public static void checknames(String[] userinput) {
List<String> error = new ArrayList<String>();
for(int i=20; i<userinput.length; i++) {
error.add(userinput[i]);
userinput[i] = null;
}
JOptionPane.showMessageDialog(null, "You can only enter up to 20
employees. \n The following employees exceed this limit." + error);
}
Just a few little changes. You should always make ArrayLists like this(with List<...>) on the left-hand side. Also, I got rid of the if statement and slightly changed your loop so you don't need it. And as everyone else mentioned, .remove(...) doesn't work with arrays.

If you insist on keeping the String[], you could delegate the "dirty work" to existing API methods, i.e. Arrays.copyOfRange(Object[] src, int from, int to)
Short, Self Contained, Correct (Compilable), Example:
import java.util.Arrays;
public class R {
public static String[] trimEmployees(String[] employees, int maxSize) {
return Arrays.copyOfRange(employees, 0, maxSize);
}
public static void main(String[] args) {
String[] employees = new String[] { "Jennifer", "Paul", "Tori",
"Zulema", "Donald", "Aleshia", "Melisa", "Angelika", "Elda",
"Elenor", "Kimber", "Eusebia", "Mike", "Karyn", "Marinda",
"Titus", "Miki", "Alise", "Liane", "Suzanne", "Dorothy" };
int max = 20;
System.out.println(String.format("Input employees (len=%d): %s ",
employees.length, Arrays.toString(employees)));
if (employees.length > max) {
employees = trimEmployees(employees, max);
System.out.println(String.format("Trimmed employees (len=%d): %s",
employees.length, Arrays.toString(employees)));
}
}
}
Prints:
Input employees (len=21): [Jennifer, Paul, Tori, Zulema, Donald, Aleshia, Melisa, Angelika, Elda, Elenor, Kimber, Eusebia, Mike, Karyn, Marinda, Titus, Miki, Alise, Liane, Suzanne, Dorothy]
Trimmed employees (len=20): [Jennifer, Paul, Tori, Zulema, Donald, Aleshia, Melisa, Angelika, Elda, Elenor, Kimber, Eusebia, Mike, Karyn, Marinda, Titus, Miki, Alise, Liane, Suzanne]

Related

ArrayList size resetting to 1 in a for loop

I am trying to find the index of a value in a nested ArrayList, but I need to find the position of the first ArrayList. I am receiving an error when I run this code:
public int findCity(String city) {
city = "\"" + city + "\"";
System.out.println(cityArray.size());
for (List<String> value : cityArray) {
String newCity = value.get(1);
if (newCity == city) return cityArray.indexOf(value);
}
return -1;
}
The problem happens in the line after the for loop:
String newCity = value.get(1);
It's telling me that index 1 is out of bounds for length 1. Any help is greatly appreciated!
I found the problem: I was using nextLine() to read the csv file, and it was creating a new array every time there was a space. This was a huge oversight on my part, but now I can start fixing the problem.
Once again, sorry for the inconvinience.
You're mixing up cityArray.size() and cityArray.get(1).size(), which can be completely different.
(You are also comparing strings with ==, which is likely to cause disaster. Use .equals.)
i think the problem is that you start counting from 1, but an ArrayList starts counting from 0. This is why the index is out of bounds.
You could try this:
String newCity = value.get(0);
Below code can help you ,though I did not understand your problem.
public static void main(String[] args) {
List<String> list1 = Arrays.asList(new String[]{"A","B"});
List<String> list2 = Arrays.asList(new String[]{"Y","Z"});
List<List<String>> cityArray = new ArrayList<>(2);
cityArray.add(list1);
cityArray.add(list2);
System.out.println(findCity("Z", cityArray));
}
public static int findCity(String city, List<List<String>> cityArray) {
System.out.println(cityArray.size());
for (List<String> value : cityArray) {
for(String newCity :value) {
if (newCity.equalsIgnoreCase(city)) {
return cityArray.indexOf(value);
}
}
}
return -1;
}

How to update an element in an array?

How can I get the Observation method to increase a single element in the numberofObs array by 1, every time I use it?
I get this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
public class Database {
private ArrayList <String> databaseOfBirds = new ArrayList<String>();
private int[] numberofObs = new int[databaseOfBirds.size()];
public void add(String name, String latinName) {
databaseOfBirds.add(name + "(" + latinName + ")");
}
public String Observation(String birdname){
for(int i = 0; i < databaseOfBirds.size(); i++) {
if(databaseOfBirds.get(i).contains(birdname)) {
numberofObs[i]++;
return "";
}
}
return "Is not a bird!";
}
}
When you create your numberofObs array it's length is zero, since at that point databaseOfBirds is empty. Unless you're growing the array in some unlisted code you'll get a NullPointerException the first time you find a bird.
You could fix this by making numberofObs a List:
private List<Integer> numberofObs = new ArrayList<>();
Then in your add method add the line:
numberofObs.add(0);
Finally, change
numberofObs[i]++;
to
numberofObs.set(i, 1 + numberofObs.get(i));
Implementation is wrong in 2 places:
numberOfObs assignment will trigger ArrayIndexOutOfBoundsException since you are not resizing it each time a new bird is added to database
you are not increasing anything on the matching bird counter
I am understanding you want to have a separate counter for each bird matched by Observation. Here you are (there are several approaches in terms of data structures, taking the one easiest to understand):
public class Database {
private List<String> databaseOfBirds = new ArrayList<>();
private List<Integer> numberofObs = new ArrayLidt<>();
public void add(String name, String latinName) {
databaseOfBirds.add(name + "(" + latinName + ")");
numberofObs.add(0);
}
public String Observation(String birdname){
for(int i = 0; i < databaseOfBirds.size(); i++) {
if (databaseOfBirds.get(i).contains(birdname)) {
numberofObs.set(i, numberofObs.get(i)+1);
System.out.println(numberofObs.get(i));
return "";
}
}
return "Is not a bird!";
}
}
I suggest using a Map instead of 2 Lists.
private Map<String, Long> birds = new HashMap<>();
Easier to manage. Unless memory is scarce, you probably don't want to use int[].

How do I store user-entered names in array to be called in a later method? I can't ask for the number of names before hand, but know max [duplicate]

I have a class - xClass, that I want to load into an array of xClass so I the declaration:
xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();
However, I don't know if I will need 10. I may need 8 or 12 or any other number for that matter. I won't know until runtime.
Can I change the number of elements in an array on the fly?
If so, how?
No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:
int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;
If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList essentially wraps an array and takes care of the logic for growing the array as required:
List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());
Generally an ArrayList is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:
class Myclass {
private int[] items;
public int[] getItems() {
return items;
}
}
you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:
class Myclass {
private List<Integer> items;
public List<Integer> getItems() {
return Collections.unmodifiableList(items);
}
}
In java array length is fixed.
You can use a List to hold the values and invoke the toArray method if needed
See the following sample:
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class A {
public static void main( String [] args ) {
// dynamically hold the instances
List<xClass> list = new ArrayList<xClass>();
// fill it with a random number between 0 and 100
int elements = new Random().nextInt(100);
for( int i = 0 ; i < elements ; i++ ) {
list.add( new xClass() );
}
// convert it to array
xClass [] array = list.toArray( new xClass[ list.size() ] );
System.out.println( "size of array = " + array.length );
}
}
class xClass {}
As others have said, you cannot change the size of an existing Java array.
ArrayList is the closest that standard Java has to a dynamic sized array. However, there are some things about ArrayList (actually the List interface) that are not "array like". For example:
You cannot use [ ... ] to index a list. You have to use the get(int) and set(int, E) methods.
An ArrayList is created with zero elements. You cannot simple create an ArrayList with 20 elements and then call set(15, foo).
You cannot directly change the size of an ArrayList. You do it indirectly using the various add, insert and remove methods.
If you want something more array-like, you will need to design your own API. (Maybe someone could chime in with an existing third party library ... I couldn't find one with 2 minutes "research" using Google :-) )
If you only really need an array that grows as you are initializing it, then the solution is something like this.
ArrayList<T> tmp = new ArrayList<T>();
while (...) {
tmp.add(new T(...));
}
// This creates a new array and copies the element of 'tmp' to it.
T[] array = tmp.toArray(new T[tmp.size()]);
You set the number of elements to anything you want at the time you create it:
xClass[] mysclass = new xClass[n];
Then you can initialize the elements in a loop. I am guessing that this is what you need.
If you need to add or remove elements to the array after you create it, then you would have to use an ArrayList.
You can use ArrayList:
import java.util.ArrayList;
import java.util.Iterator;
...
ArrayList<String> arr = new ArrayList<String>();
arr.add("neo");
arr.add("morpheus");
arr.add("trinity");
Iterator<String> foreach = arr.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());
As other users say, you probably need an implementation of java.util.List.
If, for some reason, you finally need an array, you can do two things:
Use a List and then convert it to an array with myList.toArray()
Use an array of certain size. If you need more or less size, you can modify it with java.util.Arrays methods.
Best solution will depend on your problem ;)
Arrays.copyOf() method has many options to fix the problem with Array length increasing dynamically.
Java API
Yes, wrap it and use the Collections framework.
List l = new ArrayList();
l.add(new xClass());
// do stuff
l.add(new xClass());
Then use List.toArray() when necessary, or just iterate over said List.
I recommend using vectors instead. Very easy to use and has many predefined methods for implementation.
import java.util.*;
Vector<Integer> v=new Vector<Integer>(5,2);
to add an element simply use:
v.addElement(int);
In the (5,2) the first 5 is the initial size of the vector. If you exceed the initial size,the vector will grow by 2 places. If it exceeds again, then it will again increase by 2 places and so on.
Where you declare the myclass[] array as :
xClass myclass[] = new xClass[10]
, simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.
Java Array sizes are fixed , You cannot make dynamic Arrays as that of in C++.
Yes, we can do this way.
import java.util.Scanner;
public class Collection_Basic {
private static Scanner sc;
public static void main(String[] args) {
Object[] obj=new Object[4];
sc = new Scanner(System.in);
//Storing element
System.out.println("enter your element");
for(int i=0;i<4;i++){
obj[i]=sc.nextInt();
}
/*
* here, size reaches with its maximum capacity so u can not store more element,
*
* for storing more element we have to create new array Object with required size
*/
Object[] tempObj=new Object[10];
//copying old array to new Array
int oldArraySize=obj.length;
int i=0;
for(;i<oldArraySize;i++){
tempObj[i]=obj[i];
}
/*
* storing new element to the end of new Array objebt
*/
tempObj[i]=90;
//assigning new array Object refeence to the old one
obj=tempObj;
for(int j=0;j<obj.length;j++){
System.out.println("obj["+j+"] -"+obj[j]);
}
}
}
Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).
Example:
Builder builder = IntStream.builder();
int arraySize = new Random().nextInt();
for(int i = 0; i<arraySize; i++ ) {
builder.add(i);
}
int[] array = builder.build().toArray();
Note: available since Java 8.
It is a good practice get the amount you need to store first then initialize the array.
for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store.
if you want a dynamic array you could use ArrayList() and use al.add(); function to keep adding, then you can transfer it to a fixed array.
//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList();
//add a certain amount of data
for(int i=0;i<x;i++)
{
al.add("data "+i);
}
//get size of data inside
int size = al.size();
//initialize String array with the size you have
String strArray[] = new String[size];
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
strArray[i] = al.get(i);
}
doing so is redundant but just to show you the idea, ArrayList can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List and Stack
I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:
class MyClass {
void myFunction () {
Scanner s = new Scanner (System.in);
int myArray [];
int x;
System.out.print ("Enter the size of the array: ");
x = s.nextInt();
myArray = new int[x];
}
}
this assigns your array size to be the one entered at run time into x.
Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.
import java.util.Scanner;
public class Dynamic {
public static Scanner value;
public static void main(String[]args){
value=new Scanner(System.in);
System.out.println("Enter the number of tests to calculate average\n");
int limit=value.nextInt();
int index=0;
int [] marks=new int[limit];
float sum,ave;
sum=0;
while(index<limit)
{
int test=index+1;
System.out.println("Enter the marks on test " +test);
marks[index]=value.nextInt();
sum+=marks[index];
index++;
}
ave=sum/limit;
System.out.println("The average is: " + ave);
}
}
In Java Array Sizes are always of Fixed Length But there is way in which you can Dynamically increase the Size of the Array at Runtime Itself
This is the most "used" as well as preferred way to do it-
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
In the above code we are initializing a new temp[] array, and further using a for loop to initialize the contents of the temp with the contents of the original array ie. stck[]. And then again copying it back to the original one, giving us a new array of new SIZE.
No doubt it generates a CPU Overhead due to reinitializing an array using for loop repeatedly. But you can still use and implement it in your code.
For the best practice use "Linked List" instead of Array, if you want the data to be stored dynamically in the memory, of variable length.
Here's a Real-Time Example based on Dynamic Stacks to INCREASE ARRAY SIZE at Run-Time
File-name: DStack.java
public class DStack {
private int stck[];
int tos;
void Init_Stck(int size) {
stck=new int[size];
tos=-1;
}
int Change_Stck(int size){
return stck[size];
}
public void push(int item){
if(tos==stck.length-1){
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
stck[++tos]=item;
}
else
stck[++tos]=item;
}
public int pop(){
if(tos<0){
System.out.println("Stack Underflow");
return 0;
}
else return stck[tos--];
}
public void display(){
for(int x=0;x<stck.length;x++){
System.out.print(stck[x]+" ");
}
System.out.println();
}
}
File-name: Exec.java
(with the main class)
import java.util.*;
public class Exec {
private static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int option,item,i=1;
DStack obj=new DStack();
obj.Init_Stck(1);
do{
System.out.println();
System.out.println("--MENU--");
System.out.println("1. Push a Value in The Stack");
System.out.println("2. Pop a Value from the Stack");
System.out.println("3. Display Stack");
System.out.println("4. Exit");
option=in.nextInt();
switch(option){
case 1:
System.out.println("Enter the Value to be Pushed");
item=in.nextInt();
obj.push(item);
break;
case 2:
System.out.println("Popped Item: "+obj.pop());
obj.Change_Stck(obj.tos);
break;
case 3:
System.out.println("Displaying...");
obj.display();
break;
case 4:
System.out.println("Exiting...");
i=0;
break;
default:
System.out.println("Enter a Valid Value");
}
}while(i==1);
}
}
Hope this solves your query.
You can do some thing
private static Person [] addPersons(Person[] persons, Person personToAdd) {
int currentLenght = persons.length;
Person [] personsArrayNew = Arrays.copyOf(persons, currentLenght +1);
personsArrayNew[currentLenght] = personToAdd;
return personsArrayNew;
}
You can create array with variable containing length. Like new int[n]. And pass n dynamically as argument to method. You can also create array with maximum size you can possibly need. And also create variable to track current size. depends on what your usage is.

How do you remove an elements from three parallel arrays of the same index in java?

I need to have user input the name they would like to have removed then find the index of in the array that, that name is held. Then I need to remove the name along with the price and rating. I may only use parallel arrays. I'm not sure if they other part is running successfully because I am trying to use .remove() and I get the error:
cannot find symbol
symbol: method remove(int)
location: variable array1 of type String[]
code
public static void removeGames(Scanner keyboard, String[] array1,
double[] array2, double[] array3, int currentLength)
{
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
for(int i = 0; i < array1.length; i++)
{
if(removeInput.equalsIgnoreCase(array1[i]))
{
array1.remove(i);
array2.remove(i);
array3.remove(i);
}
}
}
A few things.
Arrays don't have a remove() method. If you want to perform that operation on an Array data structure, you want to use an ArrayList.
Parallel arrays can be confusing to work with. Instead, put all the information into its own object:
class Game {
String name;
double price, rating;
}
Then you can write:
ArrayList<Game> games = new ArrayList<Game>();
The reason you are getting this error is because array objects in Java don't have a .remove() method. If you really want a dynamic collection that you can remove objects from, you should use an ArrayList.
Just replace the arrays in your method signature with ArrayLists, then in your body replace array1[i] with array1.get(i) like so:
public static void removeGames(Scanner keyboard, ArrayList<String> array1,
ArrayList<Double> array2, ArrayList<Double> array3, int currentLength) {
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
for(int i = 0; i < array1.length; i++) {
if(removeInput.equalsIgnoreCase(array1.get(i)) {
array1.remove(i);
array2.remove(i);
array3.remove(i);
}
}
}
Just make sure to import java.util.ArrayList.
There is no remove method for Array. You can use the Arraylist.remove() method.
If you really need to use array you should write your own method that removes the needed element. As java has quite an impressive collection of containers in the java.util package I would suggest using one from there. As you need to access elements at a given index I would suggest to use ArrayList. If you know the index and just want to remove the element from there use LinkedList.
I would advise also coding against the List interface, hence your code will look like this:
public static void removeGames(Scanner keyboard, List<String> array1,
List<Double> array2, List<Double> array3) {
String removeInput;
System.out.println("Enter the name of the game you would like to remove"
+ " from the list: ");
removeInput = keyboard.next();
int index = array1.indexOf(removeInput);
array1.remove(index);
array2.remove(index);
array3.remove(index);
}

Java Generating Strings Recursively - All 1s then 1 and 0

Hey guys I'm trying to get the concept of recursion down by making a program that generates String of an ArrayList recursively. My basic algorithm is:
public static ArrayList<String> generateListOfAll1sStrings(int maxBits)
terminal condition: if maxBits is 1, return the simplest case: a list containing just "1"
otherwise:
recursively call generateListOfAll1sStrings() for the next-smallest bit-length, saving the list that is returned
find the longest string in that list and create a new string with "1" appended to it (making the next-longest string)
return a new list that contains all the elements of the shorter list along with the new string just added.
The code I have so far is:
package bincomb.model;
import java.util.ArrayList;
public class BinaryCombinationGenerator {
public static ArrayList<String> generateListOfAll1sStrings(int maxBits) {
String string = null;
ArrayList<String> listofJust1 = new ArrayList<String>();
ArrayList<String> otherArray = new ArrayList<String>();
int i = 1;
if (maxBits == 1) {
listofJust1.add("1");
return listofJust1;
}
if (maxBits > 1) {
for (String string2 : listofJust1) {
String comp = "";
if (!(comp.equals(string2))) {
comp = string2;
}
string = comp;
}
listofJust1.add(i, (string + "1"));
i++;
listofJust1 = BinaryCombinationGenerator.generateListOfAll1sStrings((maxBits-1));
System.out.println(listofJust1);
return listofJust1;
}
return listofJust1;
}
public static void main(String[] args) {
generateListOfAll1sStrings(10);
}
}
However, currently, I'm returning an IndexOutOfBoundsException. I think my for loop is causing the problem, but I'm not certain how to go about fixing it.
You're getting an java.lang.IndexOutOfBoundsException at this line listofJust1.add(i, (string + "1"));.
This is because the method list.add(index, objects) tries to add the object at index "1" but your array has 0 elements.
Either change it to listofJust1.add(i-1, (string + "1")); or simply listofJust1.add((string + "1"));
#Edit: here:
listofJust1.add(i, (string + "1"));
You want to add the string for the current (N) level of recursion but below you substitute this array with:
listofJust1 = BinaryCombinationGenerator.generateListOfAll1sStrings((maxBits-1));
Which basically says "get the result for (maxBits-1) and replace with it listofJust1" therefore you are losing what you added before.
Instead you should first get the list for level N-1 and then add the string for the current level:
listofJust1 = BinaryCombinationGenerator.generateListOfAll1sStrings((maxBits-1));
listofJust1.add(stringForThisLevel);
Also you need to rething how you are computing "string" at level N, doesn't seem right.

Categories