How to Update a String Array in Java Dynamic
The Java programming language features many classes, which are digital plans or blueprints for creating virtual objects. One type of class is an array, which can hold other classes including strings, which are essentially words or sequences of text. A common and essential operation performed on string arrays is dynamic resizing: shrinking or expanding arrays during program execution so that they contain only the elements (for example, strings) they need to have. Before Java was invented, achieving this resizing required an inconvenient amount of extra programming. But Java's classes incorporated this resizing functionality, which freed programmers to concentrate on higher-level tasks.
Instructions
-
-
1
Open your Java integrated development environment (IDE) and create a new, plain Java project. Name the project "dynamicstringarrays," and name its main class "Main."
-
2
Select all code in the Main.java file and paste over it the following code:
////////////////////////////////////////////////
package dynamicstringarrays;import java.util. * ;
import java.io. * ;public class Main {
static ArrayList mylist;
static void reprintList() {
String s = "";
//Print out the input strings
for (int i = 0; i < mylist.size(); i++) {
s = "Element " + i + ":" + mylist.get(i);
System.out.println(s);
}
System.out.println("Which element number to delete?");
}public static void main(String[] args) throws Exception {
mylist = new ArrayList();// get user input until a blank line is hit
String newString = "";InputStreamReader inputStreamReader = new InputStreamReader(System. in );
BufferedReader reader = new BufferedReader(inputStreamReader);
System.out.println("Enter a string:");
newString = reader.readLine();
while (newString.length() > 0) {
mylist.add(newString);
System.out.println("Enter a string:");
newString = reader.readLine();
}//Print out the input strings
reprintList();
newString = reader.readLine();
int pos = 0;
while (newString.length() > 0) {
// delete the string
pos = Integer.parseInt(newString);
mylist.remove(pos);
//reprint list
reprintList();
newString = reader.readLine();
}
}}
//////////////////////////////////////////////// -
-
3
Run the program inside your IDE, and switch to the IDE's "Output" window. Enter any strings when the program prompts you for them. Enter one string per line, and press "Return" when you're done entering strings.
-
4
Notice that the program displays the list of strings you entered, and that it's now prompting you for the array element to delete.
-
5
Enter any number displayed in the list, then watch the display of the resulting list, which is now missing the element you chose to delete.
-
6
Delete a few more array elements, then press "Return" without entering a number when you want to end the program.
-
1