Letting a user create more than 1 object - java

I'm trying to write a program that lets the user create 2 depots.
I have it in a switch statement, but when it completes and I go back to create the second depot it overwrites depot1.
I'm not sure how I'd go about creating 2 separate depots.
do {
System.out.println("(1) Add depot number 1 ");
System.out.println("(2) Remove a depot");
System.out.println("(3) Exit program");
option = console.nextInt();
switch (option) {
case 1:
depot1 = new Depot();
if (depot1.checkDepot() == true){
System.out.println("Enter Depots name");
n = console.next();
depot1.setDepotName(n);
}
else{
System.out.println("Error only 2 depots allowed");
}
break;
case 2:
case 3:
System.exit(0);
}
}
while (option !=3);
public class Depot
{
private String name;
private Product product1, product2, product3;
static int depotCounter = 0;
// Constructor to count depot objects
public Depot(){
depotCounter++;
}
// Method to make sure no more than 2 depots are created
public boolean checkDepot(){
if (depotCounter <= 2){
return true;
}
else{
return false;
}
Is my depot class, I have a counter and a checkdepot to make sure only 2 get created.
It creates depot1 fine, but when I go into the statement again and click (1) it re-writes a new name over the object depot1

When you enter option 1, all it does is execute the code in the first "switch-case". And in there, you always use depot1 as variable. By the way, after you exit the switch statement, your depot gets lost anyways, because you declare it in that block. What you could do, is something like this:
do {
Depot depot1;
Depot depot2;
//Your code for the menu, e.g. selecting what the user wants to do
switch (option) {
case 1 :
if (depot1 == null) {
depot1 = new Depot()
//Do what you want to do with your depot
} else if (depot2 == null) {
depot2 = new Depot()
//Same as above
}
break;
//Rest of the switch statement
}
} while (option != 3)
What I did there, is just use 2 different variables for the depots, and when you want to create a new depot, you first check if you already created a depot (if e.g. depot1 points at some object, so if depot1 == null is false) and then create the corresponding depot. If you haven't created a depot at all, then depot1 IS null, so you create depot1. If you already created depot1, depot1 == null is false, so it jumps to the second if-block, checks if depot2 is null, it is, so it creates depot2. When there already are 2 depots, it does nothing.
If you want more than 2 depots, what Backpack says in his answer is your way to go.
To summarize:
a) You need different variables for your depots, not only one, so you don't just overwrite your current depot.
b) If you want your objects to persist outside of the switch statement, you need to declare them outside of it. Variables only "live" inside the block, that you declare them in.

You could try creating a list of depots and just iterate through them. That way you can add an object whenever you please to the list, or delete it from the list.
Also, you can add an identifier in the depot object, that gives like an ID or something so you can differentiate them.

int option = 0;
Depot depot;
String name;
Scanner console = new Scanner(System.in);
List<Depot> depotList = new ArrayList<>();
do {
System.out.println("(1) Add depot number ");
System.out.println("(2) Remove a depot");
System.out.println("(3) Exit program");
if (console.hasNextInt()) {
option = console.nextInt();
switch (option) {
case 1:
if (depotList.size() < 2) {
System.out.println("Enter new Depot name:");
if (console.hasNext()) {
name = console.next();
depot = new Depot();
depot.setDepotName(name);
depotList.add(depot);
}
} else {
System.out.println("Error only 2 depots allowed");
}
break;
case 2:
// remove depot code
break;
case 3:
break;
}
}
} while (option != 3);
System.out.println("Depots added:");
System.out.println("-------------");
depotList.forEach(currentDepot ->
System.out.println(currentDepot.getDepotName()));

Related

JAVA - how do I sort an ArrayList by an object element? [duplicate]

This question already has answers here:
Java to sort list of custom object on the basis of string
(7 answers)
Closed 2 years ago.
I wrote a working method to insert objects into arrayLists in my SortedArrayList class. The problem is, it sorts by the first letter of the first element of the ArrayList.
I would like to be able to choose how the ArrayList is sorted (e.g. by first letter of the surName or by the number of books in a user object. How do I approach this?
An example of the type of object stored: User(String firstName, String surName, int books)
import java.io.*;
import java.util.Scanner;
public class Driver {
//These SortedArrayLists have been derived from the sorted arraylist class
public static SortedArrayList<User> sortedUsers = new SortedArrayList<>();
public static SortedArrayList<Book> sortedBooks = new SortedArrayList<>();
//This static method checks that input matches records and then sets the loaning user information
//for the book to be loaned while incrementing the number of books held by the user.
public static void loanBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)) {
b.setLoanStatus(true);
b.setLoaningUser(user);
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()+1); //The number of books of a given object is found then incremented by one to create the new value, which is set
break;
}
}
}
//This static method checks that input matches records and clears loaning user information
//for the book to be loaned while lowering the number of books held by the user by 1.
public static void returnBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.setLoanStatus(false);
b.setLoaningUser(null);
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()-1);
//The number of books for the object instance of a user in question is decreased since they have returned a book and thus have one less book.
}
}
}
//This is the main method from which the program starts.
public static void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {
}
mainMenu(); //main menu printing method
char ch = sc.next().charAt(0);
sc.nextLine();
while (ch !='f') //the program ends as desired if f is pressed
{ switch(ch){
case 'b':
System.out.println("Displaying information about all books in the library: ");
//This toString replace method removes unwanted items for a cleaner print of book object information and removes the string description for user's name described in the user toString method.
System.out.println(sortedBooks.toString().replace("[","").replace("]","").replace("Name: ", ""));
break;
case 'u':
System.out.println("Displaying information about all users");
System.out.println(sortedUsers.toString().replace("[","").replace("]",""));
break;
case 'i':
System.out.println("Enter the loaning out data. ");
User user = readNames();
Book book = readBookName();
//A book object is created based on user input, then an attempt at altering the
// relevant object information is made via the loanBook method.
loanBook(book, user);
break;
case 'r':
System.out.println("Please the details of the book to be returned: ");
User userReturn = readNames();
Book bookReturn = readBookName();
//User input is used to create user and book objects so that a book can be returned
//by use of the returnBook method, resetting any user information about the book and decreasing the count for number of booksheld by the user.
returnBook(bookReturn, userReturn);
break;
default: //this case occurs if input does not match any of the switch statement cases.
System.out.println("Invalid input, please enter f, b, i or r");
}
mainMenu();
ch = sc.next().charAt(0);
sc.nextLine();
}
}
}
The sortedArrayList class:
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {
//This insert method ensures that an object added to an arraylist is added in a sorted order.
public void insert(E value) {
if (this.size() == 0){
this.add(value);
return; }
for (int i = 0; i < this.size(); i++) {
int comparison = value.compareTo((E) this.get(i) );
if (comparison < 0) {
this.add(i, value);
return; }
if (comparison == 0){
return; }
}
this.add(value);
}
You could simply use a regular ArrayList (or any kind of built in List) and, after you've added all elements, use Collections.sort().
Here you can guve your list as first parameter and a custom Comparator as a second. For the custom comparator you can provide your desired comparison (surname etc.).
This sort is also more efficient than what you are currently using.
Here is the JavaDoc: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)

Exiting a method with switch case in a class to the method that called it in another class

I have a class with a method that calls a method located in another class, and that method has switch cases. Th e problem is that I am not able to exit from the method with switch cases and get back to the next line after the method that called it. I have searched StackOverFlow for similar questions. I also tried to use the suggested solutions in those answers to questions related to exit from a switch case (using a conditional, using return, etc). Unfortunately, when I use these solutions, I don't go back to the next line in the method that called the switch case method. Rather, I am exiting the whole program with "Build Succeeded message".
Rather than being too abstract, I hope I am not flamed for posting some classes simulating the real problem I am facing. Sorry if the code is too long.
public class TestClass {
ClassWithriginalMethod test;
public static void main(String[] args) {
ClassWithriginalMethod g = new ClassWithriginalMethod();
g.presentMenuOptions();
}
}
This class contains the main method.
The next class is the one which have a method that calls the method with switch cases:
import java.util.ArrayList;
import java.util.Scanner;
public class ClassWithriginalMethod {
private final ArrayList<ClassWithSwitchCases> arr;
Scanner s = new Scanner(System.in);
public void presentMenuOptions() {
System.out.println(
"_____________________________________________________________________________\n"
+ "This Menu contains the following options:\n"
+ "Please choose a number corresponding to your option\n"
+ "1: to get create submenu\n"
+ "2: to get edit sub menu\n"
+ "3: to get view sub menu\n"
+ "4: to get delete sub\n"
+ "5: to exit this operation\n"
+ "_____________________________________________________________________________\n");
String str= s.nextLine();
switch (str) {
case "1":
System.out.println("Entering creation...");
this.createMenu();//This method is working properly and user is moved to nextline, i.e shown the presentMenuOptions().
break;
case "2":
System.out.println("Entering editing...");
/* The below method is the damn method that calls the other class methods with swith cases.*/
this.editMenu();
/*
** What I want is to reach the next methos below this comment when I get back from the switch case.
*/
System.out.println("We've exited from the othe class method with switch cases...");
this.presentMenuOptions();
break;
case "3":
System.out.println("Entering viewing...");
this.viewMenu();
this.presentMenuOptions();
break;
case "4":
System.out.println("Entering deletion...");
this.deleteMenu();
this.presentMenuOptions();
break;
default:
System.exit(0);
}
}
public ClassWithriginalMethod() {
this.arr = new ArrayList<>(0);
}
private void createMenu() {
ClassWithSwitchCases toBeCreated = new ClassWithSwitchCases();
this.arr.add(toBeCreated);
this.checkingArraySize();
this.presentMenuOptions();
}
private void editMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index\n");
this.arr.forEach(p -> System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName())); // we print the array to see the indices and object main elems.
int i = s.nextInt();
ClassWithSwitchCases toBeEdited = this.arr.get(i); //supposedly I am checking through another function if the object of index i is in the array.
toBeEdited.edit(toBeEdited); // it is here where we are calling the switch method in the other class
//this.presentMenuOptions();
}
private void viewMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index");
this.arr.forEach(p -> System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName())); // we print the array to see the indices and object main elems.
int i = s.nextInt();
ClassWithSwitchCases toBeViewed = this.arr.get(i); //supposedly I am checking through another function if the provided number id less than size of List.
toBeViewed.view(toBeViewed); // making this class calling the function in the other class
//this.presentMenuOptions();
}
private void deleteMenu() {
this.checkingArraySize();
System.out.println("The following objects are available. Please select the object with the corresponding index");
int i = s.nextInt();
ClassWithSwitchCases deleted = this.arr.get(i); //supposedly I am checking through another function if the provided number id less than size of List.
deleted.view(deleted); // making this class calling the function in the other class
//this.presentMenuOptions();
}
private void checkingArraySize () {
if (this.arr.size() <= 0) {System.out.println("There are no objects in the aray");}
else {
arr.stream().map((p) -> {
System.out.println("The following objects are available.");
return p;
}).forEachOrdered((p) -> {
System.out.printf("%-15s\t%-15s\t%-15s\n", "index", "fName", "sName");
System.out.printf("_____________________________________________________________________________\n");
System.out.printf("%-15d\t%-15s\t%-15s\n", arr.indexOf(p), p.getfName(),p.getsName());
});
}
}
}
The last class is the one with switch cases:
public class ClassWithSwitchCases {
private String fName;
private String sName;
Scanner s = new Scanner(System.in);
public ClassWithSwitchCases() {
System.out.println("Please enter first name");
this.fName = s.nextLine();
System.out.println("Please enter sur name");
this.sName = s.nextLine();
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
System.out.println("Please enter first name");
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
System.out.println("Please enter sur name");
this.sName = sName;
}
public void edit(ClassWithSwitchCases o) {
System.out.println(
"_____________________________________________________________________________\n"
+ "The Edit Menu contains the following options:\n"
+ "Please choose a number corresponding to your option\n"
+ "1: to edit the object's first name\n"
+ "2: to edit the object's sur name\n"
+ "3: to exit this menu\n"
+ "_____________________________________________________________________________\n");
do {
switch (s.nextLine()) {
case "1":
o.setfName(s.nextLine());
System.out.println(o.toString());// just to check if editing took place
this.edit(o); // put so that we can make other edits.
break;
case "2":
o.setsName(s.nextLine());
System.out.println(o.toString());// just to check if editing took place
this.edit(o);
break;
case "3":
System.out.println("We are leaving the method with switch cases...");
break;
default:
System.out.println("We are also leaving the method with switch cases...");
break;
}
} while ((Integer.getInteger(s.nextLine()) <= 3) && (Integer.getInteger(s.nextLine()) > 0));
}
public void view(ClassWithSwitchCases o) {
System.out.println(o.toString());
}
#Override
public String toString() {
return "_____________________________________________________________________________\n"
+ "First Name:" + this.getfName() + "\n"
+ "Middle Name:" + this.getsName() + "\n"
+ "_____________________________________________________________________________\n";
}
}
If you try to work these classes, you will notice:
I am able to execute the createMenu() method, and then I get the presentMenuOptions() method, as supposed to be.
The viewMenu() and deleteMenu() methods do their work, but they exit from the whole program.
The editMenu() method is giving me nullPointerExeption, but I have no idea which pointer is that.
I have indicated in the comments in the code what I was thinking of.
I added extra System.out.println() messages, as a way to debug my code. Since I am only a beginner, this is as far as I can go at this stage.
If there is any general value from my question it is: How to exit from a method with switch cases and go back to another method, not necessarily the main method.
Many thanks for you help and patience :)
You can use the return statement anywhere in the switch. Most likely, you want to change your break statements to return statements.
It seems to me that while my question is valid, it is not the core problem. The core problem is how do I envision my classes (Objects) and how they are related to each other. In other words, I faced this problem because of the way I orchestrated my solution. If I chose another orchestration (i.e, more proper design patterns), most probably I was not going to face this issue.
It also seems to me that beginners (I am one of them) who are serious to build a big solution will face this "problem pattern" (asking either silly questions, or evading questions like "Why you are doing this? What were you aiming to achieve?" because they run quickly into implementing certain classes while they have not figured out the overall structural, behavioral, and creational aspects of the solution.
Interestingly, though, is that by making these mistakes, they learn.
Thanks for those who answered me and those who will answer or comment.

Java enums as integers, Scanner, and menu options

I am new to Java as well as to enum types.
I am trying to make a menu selection that uses enum types as its valid choices and that displays the following integer selections for the user:
Welcome to Frank's Banking Application.
Enter:
1. Create Bank
2. Add a branch to a Bank
3. Add a customer to a Branch
4. Make a transaction with a customer
5. Display Banks, Branches, Customers, and Transactions.
6. Quit Application.
Selection ->
However, the problem I am faced with is that enum constants do not seem to accept integer values as their names. So I am stuck making them letters for now. This is the code I have so far:
import java.util.Scanner;
enum MenuOptions
{
z("Continue"), a("Create Bank"), b("Add Branch"), c("Add Customer"),
d("Make Transaction"), e("Display Information"), q("Quit");
// field
private String meaning;
// constructor
MenuOptions(String meaning)
{
this.meaning = meaning;
}
// getters
public String getMeaning()
{
return meaning;
}
}
public class Main
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Welcome to Frank's Banking Application.");
MenuOptions menuOptions = MenuOptions.z;
while (menuOptions != MenuOptions.q)
try
{
menu();
menuOptions = MenuOptions.valueOf(input.nextLine());
switch (menuOptions)
{
case a:
//createBank();
break;
case b:
//addBranch();
break;
case c:
// addCustomer();
break;
case d:
// makeTransaction();
break;
case e:
break;
case q:
System.out.println("Goodbye.");
break;
default:
System.out.println("Selection out of range. Try again");
}
}
catch (IllegalArgumentException e)
{
System.out.println("Selection out of range. Try again:");
}
}
public static void menu()
{
System.out.println("\nEnter:");
System.out.println("\ta. Create Bank");
System.out.println("\tb. Add a branch to a Bank");
System.out.println("\tc. Add a customer to a Branch");
System.out.println("\td. Make a transaction with a customer");
System.out.println("\te. Display Banks, Branches, Customers, and Transactions.");
System.out.println("\tq. Quit Application.");
System.out.print("\nSelection -> ");
}
}
As can be seen, I had to edit all the enums to have letters as their name in order to allow the user input from the scanner to match their type by using the valueOf method.
Is there a way however, to allow options: 1, 2, 3, 4, 5, 6 from user input from keyboard to be taken as a restricted enum type?
Hope that makes sense and thanks.
You can use e.g.:
MenuOptions.values()[1]
To get the second enum, numbering starts at 0.
values() is an array of all given enum values.
In your case it would be like:
MenuOptions.values()[Interger.parseInt(input.nextLine().trim()) - 1]

Instance variable with the same value for different objects although different values were assigned

First of all and before posting my question let me ask you people to stop downvoting my questions even if they seem stupid to you ,this site is an important place for me, it helps me a lot with my java doubts which are many,a question ban would be an heavy setback for me, so be helpful even by not answering!
Now for the question,
I have this method were i assign a value to a setter method with user input
public void addName() {
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add a citizen name?");
String answer = input.nextLine();
while (!answer.equals("y") || (!answer.equals("n"))) {
if (answer.equals("y")) {
String giveName = input.nextLine();
this.setName(giveName);
break;
} else if (answer.equals("n")) {
System.out.println("Not adding a name!");
break;
}else{System.out.println("Please choose y or n!");
answer = input.nextLine();}
}
}
this method is later called in main from object p1 and object p2 and being assigned a differend value for each one to the instance variable name
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Portugueses();
Pessoas p2 = new Alemaes();
p1.addName();
p2.addName();
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
but when i call the getName() method at the end of main both p1 and p2 have the same value!
Shouldn't each object get it´s own copy of an instance variable?
The Problem is in your addName()-function. Your running your loop(while (!answer.equals("y") || (!answer.equals("n")))) until a y or n is entered. So as soon as you enter it, your loop will stop.
In your loop your checking if the input that was made cotains a y or n. Now the problem should be clear. Your loop won't run with those two values entered, but inside the loop you want to check if one of those is entered.
Two little personal hints(everyone has another style): Don't use break; let your loops end themselfs. Do it with an boolean-variable and updating it's state.
The second hint would be to use one Scanner-Object. For example you could add a Scanner-parameter to your addName-function. Just init one in your MainClass.
Those hints and fixes of the problem applied to your code could look like that:
public void addName(Scanner input) {
System.out.println("Do you want to add a citizen name?");
String answer;
boolean isAnotherInputNeeded = true;
while (isAnotherInputNeeded) {
answer = input.nextLine();
if (answer.equals("y"))
{
System.out.println("What's the name?");
String giveName = input.nextLine();
this.setName(giveName);
isAnotherInputNeeded= false;
}
else if (answer.equals("n"))
{
System.out.println("Not adding a name!");
this.setName("No name entered");
isAnotherInputNeeded= false;;
}
else
{
System.out.println("Please choose y or n!");
}
input.reset();
}
}
And your MainClass:
import java.util.ArrayList;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
ArrayList<Pessoas> lista = new ArrayList<Pessoas>();
Pessoas p1 = new Pessoas();
Pessoas p2 = new Pessoas();
Scanner input = new Scanner(System.in);
p1.addName(input);
p2.addName(input);
System.out.println("You entered the following names:");
System.out.println(p1.getName());
System.out.println(p2.getName());
}
}
Hope that helps!

Java Pass object to method

I have a program that allows the user to choose between a binary search tree a splay tree and a red black tree. I wrote the class for the binary search tree and now im working on the splay tree but ive realized that my method that interacts with the user only works with the binary search tree. I set it up so that it will create an instance of whichever tree the user selects but down in my code I use only the variable that would be created if the user selected a binary search tree. My question is how can i make it so that I will only create an instance of the tree that the user selected and how can i use only one variable so that when i insert items or work on the tree i dont have to add more conditional statements for different trees?
this is what i have now
import java.util.Scanner;
import java.lang.Math.*;
public class Driver1
{
public static void main(String[] args)
{
//local variables
String treeChoice = null;
String choice = null;
String choice2 = null;
String command = null;
int insertAmount = -1;
String pattern;
int height = -1;
int i = -1;
//BST<Integer> myTree = null;
//ST<Integer> mySTTree = null;
int num = 0;
//Scanners to take user input
Scanner input = new Scanner(System.in);
Scanner inputt = new Scanner(System.in);
System.out.println("Which tree would you like to test (BST, ST, RBT)? ");
treeChoice = input.nextLine();
//Based on user input either a BST, Splay Tree, or RBT will be initialized.
if("BST".equalsIgnoreCase(treeChoice))
{
BST<Integer> myTree = new BST<Integer>();
}
else if("ST".equalsIgnoreCase(treeChoice))
{
//System.out.println("Splay Tree not ready yet");
ST<Integer> mySTTree = new ST<Integer>();
}
else if("RBT".equalsIgnoreCase(treeChoice))
{
System.out.println("RBT not ready yet");
//RBT<Integer> myTree = new RBT<Integer>();
}
else
{
System.out.println("Invalid Entry");
}
//Ask user how many items to input
System.out.println("How many items would you like to insert? ");
insertAmount = input.nextInt();
//ask user if the items will be random or sorted
System.out.println("Pattern (random or sorted): ");
choice2 = inputt.nextLine();
//If random, create random numbers
if("random".equalsIgnoreCase(choice2))
{
for(i = 1; i <= insertAmount; i++)
{
myTree.insert((int)(Math.random()*1000000)+i);
}
}
//else fill the tree with numbers in order from 1 to the user limit
else if("sorted".equalsIgnoreCase(choice2))
{
for(i = 1; i <= insertAmount; i++)
{
myTree.insert(i);
}
}
//Keep asking users input on what to do to the tree until user says quit
while(command != "quit")
{
System.out.println(
"Next command (insert X, delete X, find X, height, quit)?");
command = inputt.nextLine();
if (command.startsWith("insert"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.insert(num);
if(result == false)
{
System.out.println("Item already present.");
}
}
else if(command.startsWith("delete"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.delete(num);
}
else if(command.startsWith("find"))
{
num = Integer.parseInt(command.replaceAll("\\D", ""));
boolean result = myTree.find(num);
if(result == true)
{
System.out.println("Item present.");
}
else
{
System.out.println("Item not present.");
}
}
else if(command.startsWith("height"))
{
System.out.println("Current height of tree " + myTree.height());
}
else if(command.startsWith("quit"))
{
break;
}
System.out.println();
}
}//Close main method
as you can see I fill only myTree which would be the tree created if the user selected bst. and in the while loop i only work on myTree.
How can i make this more generic or my other idea was to take the users input and then create the instance of that tree and then pass the instance into a seperate method so that i could still use only myTree since it would refer to the instance that was passed into that method but im not sure how to pass an instance into another method. This way seems like the best but im not sure
any help is appreciated
Your trees should extend a common base class, or better, a implement common interface, say Tree, that specifies the methods to be used on all trees (find, insert, delete). Then you should have only one variable Tree myTree to which you assign an actual instance of the type the user selects.
Are you sure your above code works, however? If you do this
if("BST".equalsIgnoreCase(treeChoice))
{
BST<Integer> myTree = new BST<Integer>();
}
then the variable myTree will be unavailable after the } because the code block in which it is declared ends there. You can declare a variable at one point and assign a value to it later, like so:
Tree<Integer> myTree;
if("BST".equalsIgnoreCase(treeChoice)) {
myTree = new BinarySearchTree<Integer>();
} else if("ST".equalsIgnoreCase(treeChoice)) {
myTree = new SplayTree<Integer>();
} else if("RBT".equalsIgnoreCase(treeChoice)) {
myTree = new RedBlackTree<Integer>();
} else {
throw new IllegalArgumentException(treeChoice + " is not a valid input");
}
I very much recommend that you give your classes real names that make obvious what they represent, not just two or three letter combinations. Note that if you do not throw an exception in the last else branch, the compiler will later complain that "the variable myTree may not have been initialized".
Alternatively, you could put all your code after the tree creation if-else-statements into a method, say <T> void testTree(Tree<T> myTree) and call this method directly where you evaluate the user input, e.g. if("BST".equalsIgnoreCase(treeChoice)) testTree(new BinarySearchTree<Integer>());, but at some you will want to assign it to a variable anyway.

Categories