Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jeremy Juengel
Courses Plus Student 5,286 PointsDoes the essentially create a dynamic array?
import java.util.Scanner;
public class Arrays {
public static void main(String[] args){
String[] myString = new String[0];
String newFruit = "apple";
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 10; i++)
{
// Prompt for new fruit
System.out.print("\nEnter a new fruit: ");
// Get new fruit from user
newFruit = scan.nextLine();
// Print out what is in the old array
System.out.print("Value in old array is: ");
printArray(myString);
System.out.println();
// Add new item to array
String[] newString = addFruit(myString, newFruit);
// Copy new array into old array
myString = newString;
// Print out the new array
System.out.print("Value in new array is: ");
printArray(newString);
System.out.println("\n");
}
scan.close();
}
public static String[] addFruit(String[] currentArray, String newFruit){
//check length of current string
int currentLength = currentArray.length;
//create new array with original length + 1;
String[] newArray = new String[currentLength + 1];
//copy old array into new array
System.arraycopy(currentArray, 0, newArray, 0, currentLength);
//add new item to end of array
newArray[currentLength] = newFruit;
return newArray;
}
public static void printArray(String[] myArray){
for (String fruit : myArray ){
System.out.print(fruit + " ");
}
}
}
jcorum
71,830 Pointsjcorum
71,830 PointsNot sure what your goal is. I didn't test your work, but I'm sure you wouldn't have posted it if it doesn't work! And it does allow you to create new arrays that are larger than the original. But from a programming point of view the name of the array changes, and in many places where one would want to use a dynamic array that's a real drawback.
If your goal is to have a dynamic array, and not just an interesting programming problem, then they are already built-in to Java: ArrayLists. I have no idea how much Java you have, or whether this is old news or not. Just saying, why do all that when you can just create an ArrayList<String>?