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);
}
}
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;
}
}
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;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I've been making a login system prototype for my game, sad thing is it doesn't work! I'm not sure why but here's my code:
This is the code for my main class:`
package darkbyte.tests;
import java.util.Scanner;
public class Main {
private static FileCreator creator = new FileCreator();
private static FileReader reader = new FileReader();
private static void login() {
Scanner input = new Scanner(System.in);
boolean passwordExists;
System.out.println();
System.out.println("Please enter your username: ");
String username = input.nextLine();
System.out.println("Please enter your password: ");
String password = input.nextLine();
reader.openFile(username + ".user");
if(reader.doesStringExist(password)) {
passwordExists = true;
} else {
passwordExists = false;
}
reader.closeFile();
if(passwordExists) {
System.out.println("Welcome back to Darkbyte " + username + "!");
} else {
System.out.println("The password you entered is incorrect!");
login();
}
}
private static void register() {
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println("Please enter the username you desire: ");
String username = input.nextLine();
System.out.println("Please enter the password you desire: ");
String password = input.nextLine();
creator.openFile(username + ".user");
creator.writeString(username);
creator.writeString(password);
creator.closeFile();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Darkbyte!");
System.out.println("Would you like to login or register an account?");
System.out.println("Enter 0 to login and any other number to register: ");
int choice = input.nextInt();
if(choice == 0) {
login();
} else {
register();
}
}
}
This is the code for my FileCreator class:
package darkbyte.tests;
import java.io.*;
import java.util.*;
public class FileCreator {
private Formatter format;
public void openFile(String file) {
try {
format = new Formatter(file);
} catch(Exception e) {
System.err.println("Darkbyte: There was an error in opening the file!");
}
}
public void closeFile() {
format.close();
}
public void writeInteger(int i) {
format.format("%i%n", i);
}
public void writeFloat(float f) {
format.format("%f%n", f);
}
public void writeString(String s) {
format.format("%s%n", s);
}
public void appendInt(String file, int i) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(i);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void appendFloat(String file, float f) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(f);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void appendString(String file, String s) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println(s);
}catch (IOException e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
}
This is the code for my FileReader class:
package darkbyte.tests;
import java.io.*;
import java.util.*;
public class FileReader {
private Scanner scanner;
public void openFile(String file) {
try {
scanner = new Scanner(new File(file));
} catch(Exception e) {
System.err.println("Darkbyte: Couldn't find file!");
}
}
public void closeFile() {
scanner.close();
}
public void readInt(int i, int lookingFor) {
while(i != lookingFor) {
if(scanner.hasNext()) {
i = Integer.parseInt(scanner.next());
}
}
}
public void readFloat(float f, float lookingFor) {
while(f != lookingFor) {
if(scanner.hasNext()) {
f = Float.parseFloat(scanner.next());
}
}
}
public void readString(String s, String lookingFor) {
while(s != lookingFor) {
if(scanner.hasNext()) {
s = scanner.next();
}
}
}
public boolean doesIntExist(int i) {
boolean intIsFound = false;
int tempInt;
while(scanner.hasNext()) {
if(!intIsFound) {
tempInt = Integer.parseInt(scanner.next());
if(tempInt == i) {
intIsFound = true;
} else {
intIsFound = false;
}
}
}
return intIsFound;
}
public boolean doesFloatExist(float f) {
boolean floatIsFound = false;
float tempFloat;
while(scanner.hasNext()) {
if(!floatIsFound) {
tempFloat = Float.parseFloat(scanner.next());
if(tempFloat == f) {
floatIsFound = true;
} else {
floatIsFound = false;
}
}
}
return floatIsFound;
}
public boolean doesStringExist(String s) {
boolean stringIsFound = false;
String tempString;
while(scanner.hasNext()) {
if(!stringIsFound) {
tempString = scanner.next();
if(tempString == s) {
stringIsFound = true;
} else {
stringIsFound = false;
}
}
}
return stringIsFound;
}
}
The issue is, when I try to login, even if my username and password are correct, it still says that my details are incorrect!
I'm not sure why but can you help me out please!
I think the error is in
if(tempString == s) {
stringIsFound = true;
} else {
stringIsFound = false;
}
Change it to:
if(tempString.equals(s)) {
stringIsFound = true;
} else {
stringIsFound = false;
}
Always use equals when comparing Strings, otherwise you are comparing their reference and not their value.
You cannot compare strings like this:
if(tempString == s) {
You must use equals... So instead of == compare with equals() and fill your boolean like this:
stringIsFound = tempString.equals(s);
Your code is quite unlogical. comparing a password you entered by command line to another one you enter through the command line?
As OldProgrammer already stated: you'll need to use the .equals method to compare the Strings on value equality. == will only test them for referential equality.
Also, a small remark. Code like this:
if(reader.doesStringExist(password)) {
passwordExists = true;
} else {
passwordExists = false;
}
can easily be refactored to a slightly more efficiënt and easier to read snippet:
passwordExists = reader.doesStringExist(password);
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);
}
}