Edit: The rules are that I cannot modify the formula. The methods have to be void and I must pass the preinitialized array to those methods. These are the constraints that will be present for the future assignment itself, which is why I'm trying to play around with this namebag program this way.
I am trying to write a "namebag" program for fun and also for practice for a future assignment. The goal is to let the user have a bag. In this bag, they can store 25 names. They can add 1 name at a time, remove 1 name at a time, sort the bag so that the names are in alphabetical order, etc. Basic array exercises. I'm running into some issues since I'm not very familiar with Java, though. I have a function that takes the array, converts it into a list, attempts to add a name of the user's choice, and then attempts to convert that list BACK to the array that it once was. And then I have another function that attempts to display everything in the array.
This code works when I avoid using a menu, the switch case, and methods. I can store things into the name bag and I can display the names without any problem and without displaying the null values. But I don't understand why the names won't display in the code down below. Is there a way to get a sort of pass-by-reference effect in Java? Is there a better way to do this kind of program? I appreciate any advice!
This is my code:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
public class nameBag {
public static void main(String[] args) {
String[] nameBag = new String[25];
Scanner input = new Scanner(System.in);
while (true){
System.out.println("Welcome to the bag of names.");
System.out.println("1. Add an item to the bag.");
System.out.println("2. Display items in bag.");
System.out.println("0. Exit program.");
int userChoice = input.nextInt();
switch (userChoice){
case 1:
addName(nameBag);
break;
case 2:
displayNames(nameBag);
break;
case 0:
System.out.println("See ya!");
System.exit(0);
}
}
}
public static void addName(String[] nameBag){
ArrayList<String> nameList = new ArrayList<String>(Arrays.asList(nameBag));
Scanner input = new Scanner(System.in);
System.out.println("What name do you want to add to the pack?");
String userSelection;
userSelection = input.nextLine();
nameList.add(userSelection);
nameBag = nameList.toArray(nameBag);
}
public static void displayNames(String[] nameBag){
for (String s : nameBag) {
if (!(s == null)) {
System.out.println(s);
}
}
}
}