I am currently learning java by writing my programs from C++ to Java.
I am trying to print the data using recursive binary search tree, but its not printing
Here is my code:
public class PersonRec {
int bribe;
PersonRec lchild;
PersonRec rchild;
}
import java.util.Scanner;
public class Tree {
private PersonRec root;
public Tree()
{
root = null;
}
public void Add()
{
int aBribe;
Scanner scan = new Scanner(System.in);
System.out.println("Enter person's contribution: ");
aBribe = scan.nextInt();
Insert(root, aBribe);
}
public void Insert(PersonRec root, int aBribe)
{
if(root == null)
{
root = new PersonRec();
root.rchild = null;
root.lchild = null;
root.bribe = aBribe;
}
else if(aBribe < root.bribe)
{
Insert(root.lchild, aBribe);
}
else
{
Insert(root.rchild, aBribe);
}
}
public void view()
{
if(root == null)
{
System.out.println("Tree is empty" + "\n");
}
else
DisplayTree(root);
}
public void DisplayTree(PersonRec root)
{
if(root == null)
return;
DisplayTree(root.lchild);
System.out.println(" " + root.bribe);
System.out.println("\n");
DisplayTree(root.rchild);
}
public static void main(String args[])
{
Tree myList = new Tree();
int choice;
do
{
Scanner scan = new Scanner(System.in);
System.out.println("\nMenu\n");
System.out.println("==============================\n\n");
System.out.println("1. Add student to waiting list\n");
System.out.println("2. View waiting list\n");
System.out.println("3. Exit program \n_");
System.out.println("Please enter choice: ");
choice = scan.nextInt();
switch(choice)
{
case 1: myList.Add();
break;
case 2: myList.view();
break;
}
}
while(choice != 3);
}
}
When I type 1, i insert a bribe amount example: 23
when i type 2 again fro the menu its not being inserted in my tree it says, "tree is empty"
Thanks
In you Insert method, root is just a local variable inside the method.
And since at leaf level, null is passed, it has lost the connection with your myList.
You have to create instance for lchild before move on to Insert(root.lchild, aBribe).
import java.util.Scanner;
class PersonRec {
int bribe;
String name;
PersonRec lchild;
PersonRec rchild;
}
public class Tree {
private PersonRec root;
public Tree() {
root = null;
}
public void Add() {
Scanner scan = new Scanner(System.in);
System.out.println("Enter person's name: ");
String name = scan.next();
System.out.println("Enter person's contribution: ");
int aBribe = scan.nextInt();
this.Add(name, aBribe);
}
public void Add(String name, int aBribe) {
if (this.root == null) {
root = this.createRecord(name, aBribe);
} else {
this.Insert(root, name, aBribe);
}
}
private PersonRec createRecord(String name, int aBribe) {
PersonRec rec = new PersonRec();
rec.bribe = aBribe;
rec.name = name;
rec.rchild = null;
rec.lchild = null;
return rec;
}
private void Insert(PersonRec rec, String name, int aBribe) {
if (aBribe < rec.bribe) {
if (rec.lchild == null) {
rec.lchild = this.createRecord(name, aBribe);
} else {
Insert(rec.lchild, name, aBribe);
}
} else {
if (rec.rchild == null) {
rec.rchild = this.createRecord(name, aBribe);
} else {
Insert(rec.rchild, name, aBribe);
}
}
}
public void view() {
if (root == null) {
System.out.println("Tree is empty" + "\n");
} else
DisplayTree(root);
}
public void DisplayTree(PersonRec root) {
if (root == null)
return;
DisplayTree(root.lchild);
System.out.println(" " + root.name + ":" + root.bribe);
System.out.println("\n");
DisplayTree(root.rchild);
}
public static void main(String args[]) {
Tree myList = new Tree();
int choice;
do {
Scanner scan = new Scanner(System.in);
System.out.println("\nMenu\n");
System.out.println("==============================\n\n");
System.out.println("1. Add student to waiting list\n");
System.out.println("2. View waiting list\n");
System.out.println("3. Exit program \n_");
System.out.println("Please enter choice: ");
choice = scan.nextInt();
switch (choice) {
case 1:
myList.Add();
break;
case 2:
myList.view();
break;
}
} while (choice != 3);
}
}
Related
I've got this program here that is supposed to take in this user input and become a taco sorter. However, it's like the user isn't putting in any information to the console as it just prints out the default values of "none", "none" and "0.0" when the code should be taking this user input and be able to sort it out and print the inputted information. Any help would be great
Taco.java:
public class Taco {
private String name;
private String location;
private double price;
public Taco() {
this.name = this.location = "none";
this.price = 0.0;
}
//parameterized constructor
public Taco(String aName, String aLocation, double aPrice) {
this.setName(aName);
this.setLocation(aLocation);
this.setPrice(aPrice);
}
//accessors
public String getName() {
return this.name;
}
public String getLocation() {
return this.location;
}
public double getPrice() {
return this.price;
}
//mutators
public void setName(String aName) {
if(aName != null)
this.name = aName;
this.name = "none";
}
public void setLocation(String aLocation) {
if(aLocation != null)
this.location = aLocation;
this.location = "none";
}
public void setPrice(double aPrice) {
if(aPrice >= 0.0)
this.price = aPrice;
this.price = 0.0;
}
//toString and .equals
public String toString() {
return "Name: "+this.name+" Location: "+this.location+" Price: $"+this.price;
}
public boolean equals(Taco aTaco) {
return aTaco != null &&
this.name.equals(aTaco.getName()) &&
this.location.equals(aTaco.getLocation()) &&
this.price == aTaco.getPrice();
}
}
TacoManager.java:
import java.util.Scanner;
import java.io.*;
public class TacoManager {
//instance variable
private Taco[] tacos;
//constants
public static final int DEF_SIZE = 10;
public static final String DELIM = "\t"; //delimiter
public static final int BODY_FIELD_AMT = 3;
public static final int HEADER_FIELD_AMT = 2;
//CONSTRUCTORS
// --- default constructor ---
public TacoManager() {
init(DEF_SIZE);
}
// --- parameterized constructor ---
public TacoManager(int size) {
init(size);
}
//initialization method;
public void init(int size) {
if(size >= 1)
tacos = new Taco[size];
else
tacos = new Taco[DEF_SIZE];
}
//adding method
public void addTaco(Taco aTaco) {
//check if taco array is full
if(tacos[tacos.length-1] != null)
return;
//find the first empty space
for(int i = 0; i < tacos.length; i++) {
if(tacos[i] == null) {
tacos[i] = aTaco;
break;
}
}
this.sortTacos();
}
//remove method
public void removeTaco(String aName) {
int removeIndex = -1; //set to an index that doesn't exist for a check later
//search for element trying to remove by name
for(int i = 0; i < tacos.length; i++) {
if(tacos[i] != null && tacos[i].getName().equals(aName)) {
removeIndex = i;
break;
}
}
if(removeIndex == -1) //taco was never found
return;
else { //taco was found so shift everything to the left by 1
for(int i = removeIndex; i < tacos.length-1; i++)
tacos[i] = tacos[i+1];
//make sure the last index is ALWAYS null;
tacos[tacos.length-1] = null;
}
}
//sorting using bubble sort
private void sortTacos() {
boolean swapped = true;
while(swapped == true) {
swapped = false;
for(int i = 0; i < tacos.length-1; i++) {
if(tacos[i+1] == null) {
break; //checks if the next elements is null or not; if it is, the loop has to be stopped
}
if(tacos[i].getPrice() > tacos[i+1].getPrice()) { //out of order, swap! compare first taco and its price to its neighbor
Taco temp = tacos[i];
tacos[i] = tacos[i+1];
tacos[i+1] = temp;
swapped = true;
}
}
}
}
//write to a file!!!!!!
public void writeTacoFile(String aName) {
try {
PrintWriter fileWriter = new PrintWriter(new FileOutputStream(aName));
//Header
fileWriter.println("Taco Amt:"+DELIM+tacos.length);
//Body
for(Taco taco : tacos) {
if(taco == null)
break;
fileWriter.println(taco.getName()+DELIM+taco.getLocation()+DELIM+taco.getPrice());
}
fileWriter.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
//read from this taco file!!!
public void readTacoFile(String aName) {
try {
Scanner fileScanner = new Scanner(new File(aName));
//read the header
String fileLine = fileScanner.nextLine();
String[] splitLines = fileLine.split(DELIM);
if(splitLines.length == HEADER_FIELD_AMT) {
int size = Integer.parseInt(splitLines[1]);
init(size);
}
else
return;
//read the body!
while(fileScanner.hasNextLine()) {
fileLine = fileScanner.nextLine();
splitLines = fileLine.split(DELIM);
if(splitLines.length == BODY_FIELD_AMT) {
String name = splitLines[0];
String location = splitLines[1];
double price = Double.parseDouble(splitLines[2]);
Taco aTaco = new Taco(name, location, price);
this.addTaco(aTaco);
}
}
fileScanner.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
//print method
public void printTacos() {
for(Taco taco : tacos) {
if(taco == null)
break;
System.out.println(taco);
}
}
}
TacoManagerFE.java:
/*
* written by thomas scholz
*/
import java.util.Scanner;
public class TacoManagerFE {
private static Scanner keyboard = new Scanner(System.in); //defined here because it needs to be used across any other methods that we develop
private static TacoManager tacoManager = new TacoManager();
public static void main(String[] args) {
printGreeting();
boolean quit = false;
while(!quit) {
printChoices();
int choice = keyboard.nextInt();
keyboard.nextLine();
switch(choice) { //could be if, else if, etc
case 1:
addTaco();
break;
case 2:
removeTaco();
break;
case 3:
readTacoFile();
break;
case 4:
writeTacoFile();
break;
case 9:
quit = true;
break;
default:
System.out.println("Invalid input");
}
tacoManager.printTacos();
}
}
//greeting
public static void printGreeting() {
System.out.println("Welcome to the Taco Manager");
}
//print choices
public static void printChoices() {
System.out.println("Enter 1 to add a taco\n"
+ "Enter 2 to remove a taco\n"
+ "Enter 3 to read a taco database file\n"
+ "Enter 4 to write to a taco database file\n"
+ "Enter 9 to quit");
}
//prompt user add taco method
public static void addTaco() {
System.out.println("Enter the name of the taco");
String name = keyboard.nextLine();
System.out.println("Enter the location of the taco");
String location = keyboard.nextLine();
System.out.println("Enter the price of the taco");
double price = keyboard.nextDouble();
keyboard.nextLine();
tacoManager.addTaco(new Taco(name,location,price));
}
//prompt user remove taco method
public static void removeTaco() {
System.out.println("Enter the name of the taco to remove");
String name = keyboard.nextLine();
tacoManager.removeTaco(name);
}
//read from a taco database file method
public static void readTacoFile() {
System.out.println("Enter the file name to read a TacoDB");
String fileName = keyboard.nextLine();
tacoManager.readTacoFile(fileName);
}
//write to a taco file method
public static void writeTacoFile() {
System.out.println("Enter the file name to write a TacoDB file");
String fileName = keyboard.nextLine();
tacoManager.writeTacoFile(fileName);
}
}
Here is the output from the console:
Name: none Location: none Price: $0.0
Enter 1 to add a taco
Enter 2 to remove a taco
Enter 3 to read a taco database file
Enter 4 to write to a taco database file
Enter 9 to quit
You have the errors in these lines:
public void setName(String aName) {
if(aName != null)
this.name = aName;
this.name = "none";
}
public void setLocation(String aLocation) {
if(aLocation != null)
this.location = aLocation;
this.location = "none";
}
public void setPrice(double aPrice) {
if(aPrice >= 0.0)
this.price = aPrice;
this.price = 0.0;
}
The error is that always is executed the lines:
this.location= "none"
this.price = 0.0
this.name = "none"
You have to add an else statement:
public void setName(String aName) {
if(aName != null)
this.name = aName;
else this.name = "none";
}
public void setLocation(String aLocation) {
if(aLocation != null)
this.location = aLocation;
else this.location = "none";
}
public void setPrice(double aPrice) {
if(aPrice >= 0.0)
this.price = aPrice;
else this.price = 0.0;
}
how do I clear my memory after the fifth action?
to be able to create a new basket again and fill it with new balls.
Because now, when you re-create the basket and fill it with balls,
the error appears on the second action (filling the basket)
how to clear the cache with the first bucket so that you can enter the second one?
//main
public class Dialogue {
private static Scanner scanner = new Scanner(System.in);
private static boolean buildBasket = false;
private static boolean completedBasket = false;
private Basket basket;
private static int volumeOfBasket = 0;
public static void main(String[] args) {
boolean buildBasket = false;
boolean completedBasket = false;
Basket basket =null;
int volumeOfBasket = 0;
try {
while (true) {
System.out.println("1 - build а basket");
System.out.println("2 - add balls to basket");
System.out.println("3 - output information about basket");
System.out.println("4 - weight of balls in the basket");
System.out.println("5 - quantity red balls");
int i = ScunnerInformation.checkInformatio();
if (i == 1) {
System.out.println("what max count of ball will into basket?");
volumeOfBasket = ScunnerInformation.getVolumeBasket();
Basket newBasket = new Basket("<Basketballs>", volumeOfBasket);
System.out.println("Basket was build with name: " + newBasket.getNameBasket() +
" and with the size " + newBasket.getVolume());
buildBasket = true;
basket = newBasket;
} else if (i == 2) {
if (buildBasket) {
basket = WorkWithBasket.fillBasket(basket);
completedBasket = true;
System.out.println("you have successfully added balls to the basket");
}else {
System.out.println("error");
}
} else if (i == 3) {
if (completedBasket) {
WorkWithBasket.InfoOut(basket);
} else {
System.out.println("error");
}
}else if (i == 4) {
if (completedBasket) {
System.out.println("weight basket: " + WorkWithBasket.countWeight(basket));
} else {
System.out.println("error");
}
}else if (i==5) {
if (completedBasket) {
System.out.println(WorkWithBasket.countRedBalls(basket) + " it it number of red balls");
} else {
System.out.println("error");
}
} else if (i == 6) {
break;
}
}
}finally {
if (scanner!=null){
scanner.close();
}
}
}
//fillBasket
public class WorkWithBasket {
public static Basket fillBasket(Basket basket){
for(int i =0; i < basket.getVolume(); i++){
Ball temp = new Ball(Color.getRandomColor(), WorkWithBall.CostBall(),WorkWithBall.WeightBall());
basket.addBall(temp);
}
return basket;
}
//addBall
public void addBall(Ball ball){
if (ball !=null){
basket[ball.getId() -1] = ball;
}
}
//basket initialization
public class Basket {
private Ball[] basket;
public Basket(){
this.basket = new Ball[this.volume];
}
public Basket (String nameBasket, int volume){
this.basket = new Ball[volume];
}
public Ball[] getBasket(){
return basket.clone();
}
public void addBall(Ball ball){
if (ball !=null){
basket[ball.getId() -1] = ball;
}
}
I have an ArrayList of Objects/Items with 3 properties, Priority #, Description, and Reference #. The program is suppose to allow you to print the Item from Arraylist based on the item's reference #. For some reason the compiler won't let me iterate through the ArrayList to find the matching item.
The part I'm stuck on (inside the method 'findbyrefer'):
for(Object list : list.getMyList()){
if(list.getReference.equals(num)){
System.out.println(list);
}
My main:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myscanner = new Scanner(System.in);
boolean exit = false;
boolean error = false;
boolean error1 = false;
String input = "";
int num = 0;
System.out.println("Welcome to Your To-Do List!\n1 = Create New Item \n2 = Exit \n3 = Display Item \n4 = Delete Item");
while(exit == false){
Item item = new Item();
do{
try {
System.out.println("Enter a command ");
input = myscanner.nextLine();
num = Integer.parseInt(input);
if(num == 1){
item.reference();
System.out.println("Reference: "+ item.getReference() + "\nDescription: " + item.getDescription() + "\nPriority: " + item.getPriority());
error = true;
}
/**
* This creates the item
*/
else if(num == 2){
exit = true;
System.out.println("Bye"); break;
}
else if(num == 3){
item.findbyrefer();
/**
* This is the part I'm stuck at
*/
}
else{
error = true;
System.out.println("invalid");
}
}
catch(Exception e){
System.out.println("invalid input");
error = true;
}
}
while(error);
}
}
My Item Class:
public class Item {
private Scanner myScanner;
private int reference;
private String description;
private int priority;
List list = new List();
public void setReference(int reference) {
this.reference = reference;
}
public int getReference() {
return reference;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
}
public void setPriority(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
public void reference(){
boolean error = false;
int x = 0;
do{
try{
System.out.println("Assign this item with a reference number: ");
myScanner = new Scanner(System.in);
x=myScanner.nextInt();
setReference(x);
error=false;
break;
}
catch(Exception e){
error = true;
System.out.println("invalid");
}
} while(error);
description();
}
public void description(){
boolean error = true;
while(error){
try{
System.out.println("Enter the description: ");
myScanner = new Scanner(System.in);
String input = myScanner.nextLine();
setDescription(input);
error=false;
break;
}
catch(Exception e){
error = true;
System.out.println("invalid");
break;
}
}
priority();
}
public void priority(){
boolean error = false;
do{
try{
System.out.println("Assign this item with a priority number: ");
myScanner = new Scanner(System.in);
setPriority(myScanner.nextInt());
error=false;
}
catch(Exception e){
error = true;
System.out.println("invalid");
}
}
while(error==true);
list.addItem(this);
System.out.println(list.getMyList());
}
public void findbyrefer(){
boolean error1 = false;
String input = "";
int num = 0;
do{
try{
System.out.println("Enter the reference number of the item you want to show");
myScanner = new Scanner(System.in);
input = myScanner.nextLine();
num = Integer.parseInt(input);
for(Object list : list.getMyList()){
if(list.equals(num)){
System.out.println(list);
}
else{
System.out.println("not working");
}
}
}
catch(Exception e){
error1 = true;
System.out.println("invalid");
}
}
while(error1 = true);
}
}
My List Class that contains my actual ArrayList:
public class List {
public ArrayList<Object> MyList = new ArrayList<Object>();
public void setMyList(ArrayList<Object> myList) {
this.MyList = myList;
}
public ArrayList<Object> getMyList() {
return MyList;
}
public void addItem (Object t){
getMyList().add(t);
}
There is no getReference method on Object.
Since your ArrayList contains Items, let it know that:
ArrayList<Item> myList = new ArrayList<>();
// ------^^^^^^
Now looking at your loop:
for(Object list : list.getMyList()){
if(list.getReference.equals(num)){
System.out.println(list);
}
}
We need to:
Change Object to Item
Use a different identifier than list for the items (just to avoid confusion)
Call getReference (add ())
Use ==, not equals, to check num (equals is for objects)
So:
for (Item item : list.getMyList()) {
if (item.getReference() == num){
System.out.println(item);
}
}
Add () parenthesis for getReference method of list and use (==) equal operator.
for(Object list : list.getMyList()){
if(list.getReference() == num)){
System.out.println(list);
}
}
package pro;
import java.util.Scanner;
public class bookapp {
static book head, pointer;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to SZABIST BOOK STORE");
int choice = 0;
do {
System.out.println();
System.out.println("1. INSERT BOOK");
System.out.println("2. DELETE BOOK");
System.out.println("3. UDPATE BOOK");
System.out.println("4. SEARCH BOOK");
System.out.println("5. VIEW BOOK(S)");
System.out.println("6. EXIT");
System.out.print("Enter Choice: ");
try {
choice = Integer.parseInt(input.nextLine());
} catch (Exception e) {
e.printStackTrace();
}
switch (choice) {
case 1:
addBook();
break;
case 2:
deleteBook();
break;
case 3:
udpateBook();
break;
case 4:
searchBook();
break;
case 5:
viewBook();
break;
case 6:
input.close();
System.exit(0);
break;
default:
System.out.println("Wrong Choice TRY AGAIN!");
}
} while (true);
}
private static void viewBook() {
if (head == null) {
System.out.println("List is EMPTY !");
} else {
pointer = head;
for (book i = pointer; i != null; i = pointer.next) {
System.out.println(pointer.getBook());
pointer = pointer.next;
}
}
}
private static void searchBook() {
// TODO Auto-generated method stub
}
private static void udpateBook() {
// TODO Auto-generated method stub
}
private static void deleteBook() {
// TODO Auto-generated method stub
}
public static void addBook() {
if (head == null) {
String details[] = enterDetails();
pointer = new book(details[0], details[1], details[2]);
head = pointer;
pointer.next = null;
} else {
String details[] = enterDetails();
pointer.next = new book(details[0], details[1], details[2]);
pointer = pointer.next;
pointer.next = null;
}
}
public static String[] enterDetails() {
String[] details = new String[3];
try {
String title;
String ISBN;
System.out.print("Please enter Book Title: ");
title = input.nextLine();
System.out.print("Please enter Book ISBN: ");
ISBN = input.nextLine();
String authors;
System.out.print("Enter Book author(s): ");
authors = input.nextLine();
details[0] = title;
details[1] = ISBN;
details[2] = authors;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return details;
}
}
//class
package pro;
public class book {
String[] authors;
static String publisher;
final String ISBN;
final String title;
book next;
book(String title, String ISBN, String... authors){
this.ISBN = ISBN;
this.title = title;
this.authors = new String[authors.length];
int i=0;
for (String s: authors){
this.authors[i]=s;
i++;
}
}
public String getBook(){
return "BOOK TITLE: " + this.title + "\n" + "BOOK ISBN: " + this.ISBN +
"\n" + "BOOK AUTHOR(S):" + getAuthors() +"\n"
;
}
public String getAuthors(){
StringBuilder s = new StringBuilder();
for (String s1: this.authors){
s.append(s1 + ",");
}
return s.toString();
}
}
want to add search Book update book delete Book in linked list in java
when i press 2 it update book
when i press 3 it search Book
when i press 4 it delete book
In linked list in java.
cant find the way out
Call this with the book id to search from your search method.
private static void Book searchBook(int book_id) {
if(head == null)
return null;
Book iterator = head;
while(iterator != null){
if(iterator.getId() == book_id){
return iterator;
}
iterator = iterator.next;
}
return null;
}
The user must input a key to a node, and pick one of the three order choices. They can press the indicated number to perform an operation. I need this code as soon as possible because finals is coming :(
import java.io.*;
import java.util.*;
public class BinaryTree {
public static int choice,listLength;
Node root;
public void addNode(int key, String name) {
Node newNode = new Node(key, name);
if (root == null) {
root = newNode;
} else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (key < focusNode.key) {
focusNode = focusNode.leftChild;
if (focusNode == null) {
parent.leftChild = newNode;
return;
}
} else {
focusNode = focusNode.rightChild;
if (focusNode == null) {
parent.rightChild = newNode;
return;
}
}
}
}
}
public void inOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
inOrderTraverseTree(focusNode.leftChild);
System.out.println(focusNode);
inOrderTraverseTree(focusNode.rightChild);
}
}
public void preorderTraverseTree(Node focusNode) {
if (focusNode != null) {
System.out.println(focusNode);
preorderTraverseTree(focusNode.leftChild);
preorderTraverseTree(focusNode.rightChild);
}
}
public void postOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
postOrderTraverseTree(focusNode.leftChild);
postOrderTraverseTree(focusNode.rightChild);
System.out.println(focusNode);
}
}
public Node findNode(int key) {
Node focusNode = root;
while (focusNode.key != key) {
if (key < focusNode.key) {
focusNode = focusNode.leftChild;
} else {
focusNode = focusNode.rightChild;
}
if (focusNode == null)
return null;
}
return focusNode;
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String x;
int y;
BinaryTree theTree = new BinaryTree();
theTree.inOrderTraverseTree(theTree.root);
do
{
try
{
System.out.println("Choose: ");
System.out.println("[1]Insert ");
System.out.println("[2]Delete ");
System.out.println("[3]Display ");
System.out.println("[4]Search");
System.out.println("[5]Exit");
System.out.println("====================");
choice = Integer.parseInt(br.readLine());
switch(choice)
{
case 1 : System.out.println("INSERT");
System.out.println("Enter a key: ");
y = Integer.parseInt(br.readLine());
System.out.println("Enter a name: ");
x = br.readLine();
theTree.addNode(y,x);
System.out.println("Tree: " + theTree.findNode(y));
break;
case 2 : System.out.println("DELETE");
System.out.println("Enter the node to remove: ");
x = br.readLine();
case 3 : System.out.println("DISPLAY");
System.out.println("In Order");
theTree.inOrderTraverseTree(theTree.root);
System.out.println("");
System.out.println("PreOrder");
theTree.preorderTraverseTree(theTree.root);
System.out.println("");
System.out.println("PostOrder");
theTree.postOrderTraverseTree(theTree.root);
System.out.println("");
case 4 : System.out.println("SEARCH");
System.out.println("Enter a key to find: ");
int z = Integer.parseInt(br.readLine());
//for(int i = 0; i<listLength;i++)
//{
if(theTree.findNode(z)!= null){
System.out.println("Found it! : " + theTree.findNode(z) );
}
else{
System.out.println("ERROR: Not found!");
}
break;
case 5 : System.out.println("Bye");
break;
default : System.out.println("Try Again");
break;
}
}catch(NumberFormatException e)
{
System.out.println("Try again");
}
}while(choice != 5);
}
}
Node Class :->
package com.shi.tree;
public class Node {
private int key;
private String name;
private Node leftChild,rightChild;
public Node(int key, String name) {
this.key = key;
this.name=name;
// TODO Auto-generated constructor stub
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
public Node getRightChild() {
return rightChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
#Override
public String toString() {
System.out.println("key :"+this.getKey()+" Name :"+this.getName());
// TODO Auto-generated method stub
return super.toString();
}
}
BinaryTree Class :->
package com.shi.tree;
import java.io.*;
import java.util.*;
import com.shi.tree.Node;
public class BinaryTree {
public static int choice,listLength;
Node root;
public void addNode(int key, String name) {
Node newNode = new Node(key, name);
if (root == null) {
root = newNode;
} else {
Node focusNode = root;
Node parent;
while (true) {
parent = focusNode;
if (key < focusNode.getKey()) {
focusNode = focusNode.getLeftChild();
if (focusNode == null) {
parent.setLeftChild(newNode);
return;
}
} else {
focusNode = focusNode.getRightChild();
if (focusNode == null) {
parent.setRightChild(newNode);
return;
}
}
}
}
}
public void inOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
inOrderTraverseTree(focusNode.getLeftChild());
System.out.println(focusNode.toString());
inOrderTraverseTree(focusNode.getRightChild());
}
}
public void preorderTraverseTree(Node focusNode) {
if (focusNode != null) {
System.out.println(focusNode);
preorderTraverseTree(focusNode.getLeftChild());
preorderTraverseTree(focusNode.getRightChild());
}
}
public void postOrderTraverseTree(Node focusNode) {
if (focusNode != null) {
postOrderTraverseTree(focusNode.getLeftChild());
postOrderTraverseTree(focusNode.getRightChild());
System.out.println(focusNode);
}
}
public Node findNode(int key) {
Node focusNode = root;
while (focusNode.getKey() != key) {
if (key < focusNode.getKey()) {
focusNode = focusNode.getLeftChild();
} else {
focusNode = focusNode.getRightChild();
}
if (focusNode == null)
return null;
}
return focusNode;
}
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String x;
int y;
BinaryTree theTree = new BinaryTree();
theTree.inOrderTraverseTree(theTree.root);
do
{
try
{
System.out.println("Choose: ");
System.out.println("[1]Insert ");
System.out.println("[2]Delete ");
System.out.println("[3]Display ");
System.out.println("[4]Search");
System.out.println("[5]Exit");
System.out.println("====================");
choice = Integer.parseInt(br.readLine());
switch(choice)
{
case 1 : System.out.println("INSERT");
System.out.println("Enter a key: ");
y = Integer.parseInt(br.readLine());
System.out.println("Enter a name: ");
x = br.readLine();
theTree.addNode(y,x);
System.out.println("Tree: " + theTree.findNode(y));
break;
case 2 : System.out.println("DELETE");
System.out.println("Enter the node to remove: ");
x = br.readLine();
case 3 : System.out.println("DISPLAY");
System.out.println("In Order");
theTree.inOrderTraverseTree(theTree.root);
System.out.println("");
System.out.println("PreOrder");
theTree.preorderTraverseTree(theTree.root);
System.out.println("");
System.out.println("PostOrder");
theTree.postOrderTraverseTree(theTree.root);
System.out.println("");
case 4 : System.out.println("SEARCH");
System.out.println("Enter a key to find: ");
int z = Integer.parseInt(br.readLine());
//for(int i = 0; i<listLength;i++)
//{
if(theTree.findNode(z)!= null){
System.out.println("Found it! : " + theTree.findNode(z) );
}
else{
System.out.println("ERROR: Not found!");
}
break;
case 5 : System.out.println("Bye");
break;
default : System.out.println("Try Again");
break;
}
}catch(NumberFormatException e)
{
System.out.println("Try again");
}
}while(choice != 5);
}
}
The major issue is that you definitely have not defined Node class , at least not from the code you've provided, despite what you may think.
If you put that code into and IDE (Integrated Development Environment) like Eclipse (which I highly recommend you do since you are new to Java and short on time), you'll see it showing a lot of errors because it can't find your definition of Node. Use these error message to help you work out what is wrong with your code.
Hint: if your class definition is in the same file BinaryTree.java, it begins like this:
class Node {
/* Your code defining the node class */
}
You might also want to clean up the formatting of your code, because as it currently stands it is hard to read and this will make it harder for you in the long run to debug and get your code working as needed.
Everyone here wants to make sure you pass your finals, but you have to actually understand what is going on with your code and why it isn't working. There's no shortcut, work through it methodically, check any errors you get with SO or other sites and pass your finals!