My Array and Int keep resetting values when their method runs - java

I'm currently doing an assignment which requires me to use classes to make an album collection manager. I've been debugging and came across a problem. The Album[] is supposed to hold all the Album objects while numAlbums is supposed to keep track of the number of albums, but when I run the add method, it will increment the numAlbums and add the album to Album[], but once the method ends, it will reset instead of staying where it should be.
This is a problem especially since I can't print the album list since it relies on the numAlbums incrementing in value.
public class Collection {
private Album[] albums;
private int numAlbums; //number of albums currently in the collection
//find the album index, or return NOT_FOUND
private int find(Album album)
{
String title = album.getTitle(); // First, put the title and artist in string variables.
String artist = album.getArtist();
for (int i = 0; i < albums.length; i++) // Let's find this album.
{
Album c = new Album(); // Make Album c so we can compare every album.
c = albums[i];
if (title == c.getTitle() && artist == c.getArtist()) // If the title and artist match, then return the index.
{
return i; // We found the album!
}
}
return -1; // Album doesn't exist.
}
//increase the capacity of the array list by 4
private void grow()
{
Album[] temp = new Album[getAlbums() + 4]; // Create new temp array with 4 more spaces.
for (int i = 0; i < albums.length; i++) // Use loop to insert all values from albums to temp.
{
temp[i] = albums[i];
}
albums = temp; // Overwrite previous albums with new one.
}
// Add an Album. Command A.
public boolean add(Album album)
{
int counter = 1;
if (getAlbums() == 0) // If there are no albums, grow the list to the first 4 indexes.
{
Album[] temp = new Album[numAlbums + 4];
albums = temp;
}
else if (getAlbums() > 0)
{
Album search = new Album();
for (int i = 0; i < albums.length; i++) // Check if the album has the same title and artist in the collection.
{
search = albums[i];
if (album.getTitle().equals(search.getTitle()) && album.getArtist().equals(search.getArtist()) == true)
{
return false;
}
}
}
int a = getAlbums();
albums[a] = album; // Put the album in the collection.
a++; // Increase the amount of albums.
setAlbums(a);
if (numAlbums == 4 * counter) // If the number of albums reach multiples of 4, then increase the array and counter.
{
grow();
counter++;
}
for (int i = 0; i < albums.length; i++)
{
System.out.println(albums[i]); // Simple print of the list.
}
return true;
}
// Remove an Album. Command D.
public boolean remove(Album album)
{
if (find(album) == -1) // First, find the album to remove.
{
return false; // That album does not exist.
}
else // The album exists.
{
int index = find(album); // Copy the index number.
for (int i = index; i < albums.length; i++)
{
albums[i] = albums[i + 1]; // Shift the elements to the left by 1.
}
}
int a = getAlbums();
a--; // Decrease the amount of albums.
setAlbums(a);
return true; // We removed it.
}
//set to not available. Command L.
public boolean lendingOut(Album album)
{
if (find(album) == -1) // First, find the album to lend.
{
return false; // That album does not exist.
}
else // The album exists.
{
if (album.isAvailable() == false)
{
return false;
}
else
{
album.setAvailable(false);
}
}
return true; // We removed it.
}
//set to available. Command R.
public boolean returnAlbum(Album album)
{
if (find(album) == -1) // First, find the album to lend.
{
return false; // That album does not exist.
}
else // The album exists.
{
if (album.isAvailable() == true)
{
return false;
}
else
{
album.setAvailable(true);
}
}
return true; // We removed it.
}
//display the list without specifying the order. Command P.
public void print()
{
int y = getAlbums();
if (y == 0) // If the collection is empty, then return empty.
{
System.out.println("The collection is empty!");
return;
}
for (int i = 0; i < albums.length; i++)
{
System.out.println(albums[i]); // Simple print of the list.
}
}
//display the list sorted by the release date. Command PD.
public void printByReleaseDate()
{
if (getAlbums() == 0) // If the collection is empty, then return empty.
{
System.out.println("The collection is empty!");
return;
}
Album[] SortAlbumsRelease = new Album[numAlbums]; // Make another array to store the album list order.
for (int i = 0; i < albums.length; i++)
{
SortAlbumsRelease[i] = albums[i]; // Copy the contents of the array.
}
Album First = new Album(); // Create temp albums so we can compare.
Album Second = new Album();
Album temp = new Album();
for (int o = 0; o < albums.length; o++) // Go through every single album.
{
for (int p = 0 + 1; p < albums.length; p++)
{
First = SortAlbumsRelease[o];
Second = SortAlbumsRelease[p];
int compare = First.getReleaseDate().compareTo(Second.getReleaseDate()); // Use the compare method from date to get a value.
if (compare == -1) // If the first value is lower, then put that album in the previous slot.
{
temp = SortAlbumsRelease[o];
SortAlbumsRelease[o] = SortAlbumsRelease[p];
SortAlbumsRelease[p] = temp;
}
}
}
for (int i = 0; i < albums.length; i++) // Print the list.
{
System.out.println(SortAlbumsRelease[i]);
}
}
//display the list sorted by the genres. Command PG.
public void printByGenre()
{
if (getAlbums() == 0) // If the collection is empty, then return empty.
{
System.out.println("The collection is empty!");
return;
}
Genre type = null; // Set the genre type.
Album Temp = new Album(); // Make a temp album.
for (int i = 0; i <= 4; i++) // Iterate through all the genre cases.
{
switch(i)
{
case 0:
type = Genre.Classical;
case 1:
type = Genre.Country;
case 2:
type = Genre.Jazz;
case 3:
type = Genre.Pop;
case 4:
type = Genre.Unknown;
}
for (int j = 0; j < albums.length; j++) // Look through the albums that have the matching genre.
{
Temp = albums[j];
if (Temp.getGenre() == type) // If they match, print in that order.
{
System.out.println(albums[j]);
}
}
}
}
public int getAlbums()
{
return numAlbums;
}
public void setAlbums(int m)
{
numAlbums = m;
}
}
Below is the manager we have to create when running the program. We also use an album, genre, and date class, but I feel like the problem is somewhere in these areas.
import java.util.Scanner;
public class CollectionManager
{
public void run()
{
System.out.println("Collection Manager starts running."); // Begin.
while(true)
{
Scanner input = new Scanner(System.in);
String collect = input.nextLine(); // Take the input in.
String[] output = collect.split(","); // Creates an array "output" and splits the input by commas.
// Below is the designated spots for array "output" after the split.
// A,Change,Anika,pop,7/23/2021
//[0] [1] [2] [3] [4]
switch(output[0])
{
case "A": // Add the album.
Album a = new Album();
if (a.MakeAlbum(output) == true) // If the output goes well and returns true, then add to the collection.
{
Collection add = new Collection();
if (add.add(a) == true) // If true, add the album.
{
System.out.println(a + " >> added.");
break;
}
else // Otherwise, it's already in there.
{
System.out.println(a + "is already in the collection.");
break;
}
}
else // If the date is invalid, then return Invalid Date!
{
System.out.println("Invalid Date!");
break;
}
case "D": // Delete an Album.
Album d = new Album();
d.MakeAlbum(output);
Collection delete = new Collection();
if (delete.remove(d) == true) // If the album is in the collection, delete.
{
System.out.println(d.getTitle() + "::" + d.getArtist() + " >> deleted.");
break;
}
else // Otherwise, it doesn't exist.
{
System.out.println(d.getTitle() + "::" + d.getArtist() + " >> is not in the collection.");
break;
}
case "L": // Lend an Album.
Album l = new Album();
l.MakeAlbum(output);
Collection lend = new Collection();
if (lend.lendingOut(l) == true) // If the album is in the collection, lend.
{
System.out.println(l.getTitle() + "::" + l.getArtist() + " >> lending out and set to not available.");
break;
}
else // Otherwise, it doesn't exist or can't be lend out.
{
System.out.println(l.getTitle() + "::" + l.getArtist() + " >> is not available.");
break;
}
case "R": // Return the album.
Album r = new Album();
r.MakeAlbum(output);
Collection ret = new Collection();
if (ret.returnAlbum(r) == true) // If the album is in the collection, return.
{
System.out.println(r.getTitle() + "::" + r.getArtist() + " >> returning and set to available.");
break;
}
else // Otherwise, it doesn't exist or can't be returned.
{
System.out.println(r.getTitle() + "::" + r.getArtist() + " return cannot be completed.");
break;
}
case "P": // Print with no order.
Collection Print = new Collection();
Print.print(); // Print the album list.
break;
case "PD": // Print with release date order.
Collection PrintD = new Collection();
PrintD.printByReleaseDate();; // Print the album list by release date.
break;
case "PG": // Print with genre order.
Collection PrintG = new Collection();
PrintG.printByGenre(); // Print the album list by genre.
break;
case "Q": // Quit the program.
System.out.println("Collection Manager terminated.");
return; // The end.
default: // Invalid. Try again.
System.out.println("Invalid command!");
break;
}
}
}
}
I can't find anything on google relating to the problem so any help is appreciated.

The problem is that you're creating a new collection object per switch statement. Instead, create the object prior to your while loop.
//initialize collection object prior to while loop
Collection myCollection = new Collection();
while(true){
Scanner input = new Scanner(System.in);
String collect = input.nextLine();
String[] output = collect.split(",");
switch(output[0]){
case "A":
Album a = new Album();
if(a.MakeAlbum(output) == true)
{
//adding to the same collection object created previously
if (myCollection.add(a) == true)
{
System.out.println(a + " >> added.");
break;
}
else
{
System.out.println(a + "is already in the collection.");
break;
}
}
else
{
System.out.println("Invalid Date!");
break;
}
case "D":
Album d = new Album();
d.MakeAlbum(output);
//removing from same collection object created previously
if (myCollection.remove(d) == true)
{
System.out.println(d.getTitle() + "::" + d.getArtist() + " >> deleted.");
break;
}
else
{
System.out.println(d.getTitle() + "::" + d.getArtist() + " >> is not in the collection.");
break;
}
}
}
Should be all that takes to make your program work, now you're always just adding and subtracting from a single Collection object. Before, you were creating a new collection object per switch, and these objects couldn't be accessed at the end of the while loop.
Do this for the rest of your switch statements! I've only done the first two here. Let me know if it runs!

Related

How to Delete a Record from a csv file with arrays in java

I just want to know when you overwrite the elements for deleting a certain element , you change the position of all the elements after it.The thing is when you change the position the last element in the last element will be same as the second last. here in this code i am changing the last element to be empty which i don't want . I just want to remove it so i can save it in csv. If i write null then it saves 'null' in csv as a record which i dont want! Please help!
public static void deleteEntry() {
int flag = -1;
Boolean found = false;
System.out.println("Please provide the name of the contact to delete its entry: ");
String searchName2 = sc.next().toUpperCase();
System.out.println(counter);
try {
for (int i = 0; i < counter; i++) {
if (names[i].compareTo(searchName2) == 0) {
flag = i;
found = true;
}
}
} catch (Exception e) {
}
if (flag == -1) {
System.out.println("Contact Name NOT Found");
} else { //record was found, flag is a positive index position
//if the record is the last record, simply remove it and decrement the counter
if (flag == counter - 1) {
System.out.println("Contact Deleted!");
names[flag] = null;
numbers[flag] = null;
counter--;
}else {
//record is not the last record, shift all later records down
for (int i = flag; i < counter-1; i++){
names[i] = names[i + 1];
numbers[i] = numbers[i + 1];
}
System.out.println(counter);
System.out.println("Contact Deleted!");
if (names[counter-1].equals(names[counter-2])) {
names[counter-1] = "";
numbers[counter-1] = "";
}
}
}

Head First Java book battleship game

I am reading "Head First Java" book and I came across the problem in chapter 5 with the battleship game (with simple version). I knew that the book's code doesn't work and I tried my self fixing it, but it still didn't work.
So tried to google it and I found some post on this website but I still have a problem. The game isn't working properly as it should.
If a player enters any random number, the output is always "hit"...
This is the last version of the code:
DotCom class:
public class DotCom {
private ArrayList<String> locationCells = new ArrayList<>();
public void setlocationCells(int[] loc) {
if (loc != null)
for (int val : loc)
locationCells.add(String.valueOf(val));
}
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
}
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
System.out.println(result);
return result;
}
}
DotComGame class:
public class DotComGame {
public static void main(String[] args) {
int guessingTimes = 0;
DotCom dot = new DotCom();
GameHelperrr helper = new GameHelperrr();
int randomNum = (int) (Math.random() * 5);
int[] locations = { randomNum, randomNum + 1, randomNum + 2 };
dot.setlocationCells(locations);
boolean isAlive = true;
while (isAlive == true) {
String guess = helper.getUserInput("Enter a number");
String result = dot.checkYourself(guess);
guessingTimes++;
if (result.equals("kill")) {
isAlive = false;
System.out.println("You took " + guessingTimes + " guesses");
}
}
}
}
I would really appreciate to get a detailed and understandable answer, because I'm stuck and I couldn't move on with the book for a few days now.
int index = locationCells.indexOf(userInput);
This method will return -1 if the element doesn't exist in the collection.
So if you miss, it won't hit this condition:
if (index >= 0) {
locationCells.remove(index);
}
There are still elements in this collection because you didn't remove anything...
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = "hit";
}
So on a miss, the result still shows "hit."
Try this instead:
if (locationCells.isEmpty()) {
result = "kill";
} else {
result = index == -1 ? "miss" : "hit";
}
If you haven't killed the opponents ships, then you either miss all ships or you hit a single ship.
I would guess the checkYourself-Method must be like this:
public String checkYourself(String userInput) {
String result = "miss";
int index = locationCells.indexOf(userInput);
if(index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}else {
result = "hit";
}
}
System.out.println(result);
return result;
}
In it's current form the ArrayList is never empty because you insert 3 Values but only remove 1 if the user-input is in the list so .isEmpty() is never TRUE.

Java: Dividing a single array by a object element value in to 2 arrays

Edit. thank you.
I have an array of 'normal' vehicles and 'large' vehicles. I have an assignment requiring me to divide them up to contribute to a far larger app.
One array for the large vehicles, one for the normal vehicles containing all the info for each element. ArrayLists are not permitted as my instructor is teaching us fundamentals.
Sample of the array
27723 4/09/61 large 7337
28507 22-02-1983 large 7055
28558 1/05/70 normal 3518
//On button press
//recieve single item from array from main and test it
//array in main will be looped for all elements.
public String loadVehicle(Vehicle v) {
String res = Constants.OK;
boolean normBool = false;
boolean largeBool = false;
//if both arrays are full , stop the method call in the main form
if (normBool && largeBool){return Constants.ERROR;}
//if vehicle size is normal, fill the normal veh array
if(v.getSize().equals(Constants.NORMAL_SIZE))
{
for(int i = 0; i<normalVehicles.length; i++)
{
//if norm veh array element is null, add the appropriate value to it
if(normalVehicles[i] == null){normalVehicles[i] = v;}
else{normBool = true;}
}
}
//if veh size is large put it in the large veh array
else if(v.getSize().equals(Constants.LARGE_SIZE))
{
for(int iL = 0; iL<largeVehicles.length; iL++)
{
if(largeVehicles[iL] == null){largeVehicles[iL] = v;}
else{largeBool = true;}
}
}
return res;
}//end method
Seems you cannot use builtin LinkedList class too, then do this:
Add the following code in your Vehicle class:
class Vehicle(){
//YOUR OTHER PIECES OF CODES ...
private static Vehicle firstLargeVehicle;
private Vehicle nextLargeVehicle;
private int index;
public void setIndex(int index){
this.index = index;
if(index == 0) Vehicle.firstLargeVehicle = this;
}
public int getIndex(){
return index;
}
public void setNextLargeVehicle(Vehicle nextLargeVehicle){
this.nextLargeVehicle = nextLargeVehicle;
}
public Vehicle getNextLargeVehicle(){
return nextLargeVehicle;
}
public addLargeVehicle(Vehicle newVehicle){
this.nextLargeVehicle = newVehicle;
newVehicle.setIndex(index + 1);
}
public getListSize(){
Vehicle lastOne = this;
while (lastOne.getNextLargeVehicle() != null){
lastOne = lastOne.getNextLargeVehicle();
}
return lastOne.getIndex() + 1;
}
public static Vehicle[] largeVehiclesToArray(){
Vehicle[] result = new Vehicle[firstLargeVehicle.getListSize()]();
Vehicle pointer = firstLargeVehicle;
for (int counter = 0; pointer != null; counter ++){
result[counter] = pointer;
pointer = pointer.getNextLargeVehicle();
}
return result;
}
}
And in your main loop, do something like the following code:
Vehicle vehicle = null;
for(Vehicle newVehicle : allVehicles) {
if (newVehicle.isLarge()){
if (vehicle == null) {
vehicle = newVehicle;
vehicle.setIndex(0);
}else{
vehicle.addLargeVehicle(newVehicle));
}
}
}
Vehicle[] largeVehicles = Vehicle.largeVehiclesToArray();
And the same story goes for normal vehicles.
Any question ?
You can write your loops like this:
for(int i = 0; i < normalVehicles.length; i++)
{
if(normalVehicles[i] == null)
{
normalVehicles[i] = v;
break;
}
}
// if last slot isn't null then it's full
normBool = normalVehicles[normalVehicles.length-1] != null;

Error using linked list remove function. after advanced for loop breaks

I am trying to get my bet system to detect if the input numbers are duplicates. When you run the program, press 2 on the "for box" bet and follow instructions from there. The issue lies in the winlose duplicate and also for the non duplicate. I don't know how I am supposed to fix the issue.
Error stacktrace :
at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
at java.util.LinkedList$ListItr.next(LinkedList.java:888)
at numbersgame.Test.winLoseBetDuplicate(NumbersGame.java:190)
at numbersgame.Test.checkDuplicate(NumbersGame.java:167)
at numbersgame.Test.WinLoseBox(NumbersGame.java:134)
at numbersgame.Test.getValues(NumbersGame.java:117)
at numbersgame.NumbersGame.main(NumbersGame.java:24)
C:\Users\cymmm1\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)
Code :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package numbersgame;
import java.lang.reflect.Array;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
/**
*
* #author cymmm1
*/
public class NumbersGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Test numbers = new Test();
numbers.getValues();
boolean win = numbers.win; //this checks if you won, either as a duplicate or not.
if (win) {
System.out.println("You won");
switch (numbers.bet_Type) {
case 1:
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 600 + " back.");
break;
case 2:
if (numbers.dupwin) {
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 200 + " back.");
} else {
System.out.println("You waged " + numbers.bet_Amount
+ "dollars and you will get "
+ numbers.bet_Amount * 100 + " back.");
}
break;
}
} else {
System.out.println("Sorry, you lost $" + numbers.bet_Amount + " dollars");
}
System.exit(0);
}
}
class Test {
public int bet_Type;
public int bet_Amount;
public int player_Number;
public int winning_Number;
private JOptionPane panel;
public boolean win;
public List<Integer> digits = new LinkedList<>();
List<Integer> digits2 = new LinkedList<>();
public void getValues() {
panel = new JOptionPane();
this.bet_Type = (Integer.parseInt(panel.showInputDialog("What is the bet type. 1 for straight, 2 for box")));
this.bet_Amount = (Integer.parseInt(panel.showInputDialog("How much is the bet")));
boolean bad = true;
while (bad) {
this.player_Number = (Integer.parseInt(panel.showInputDialog("What is the player's Number. 3 numbers must be inputted")));
int playerNumCopy = this.player_Number;
while (playerNumCopy > 0) {
digits.add(0, playerNumCopy % 10);
playerNumCopy = playerNumCopy / 10;
}
int lengthOfNum = digits.size();
if (lengthOfNum != 3) {
bad = true;
} else {
bad = false;
}
}
bad = true;
while (bad) {
this.winning_Number = (Integer.parseInt(panel.showInputDialog("What is the winning Number")));
int winningnumbercopy = this.winning_Number;
while (winningnumbercopy > 0) {
digits2.add(0, winningnumbercopy % 10);
winningnumbercopy = winningnumbercopy / 10;
}
int lengthOfNum = digits2.size();
if (lengthOfNum != 3) {
bad = true;
} else {
bad = false;
}
}
//========END OF CHECK FOR PROPER NUMBERS=================================
//Now to check for type of bet and se the method appropriate
if (this.bet_Type == 1) {
win = WinLoseStraight();
} else {
win = WinLoseBox();
}
}
private boolean WinLoseStraight() {
if (this.player_Number == this.winning_Number) {
return true;
} else {
return false;
}
// this goes back to getValues
}
private boolean WinLoseBox() {
//this checks for duplicates. if it isnt a duplicate then check for a box non-dup
boolean duplicatewin = checkDuplicate();
if (duplicatewin) { //you either won with a duplicate number or nonduplicate. check Duplicate does to things at once
return true;
} else {
return false;
}
}
public boolean duplicate;
public boolean dupwin;
//this checks for duplicated numbers
public boolean checkDuplicate() {
duplicate = false;
int[] array = new int[digits.size()];
int i = 0;
for (int numbers : digits) {
array[i] = numbers;
System.out.println(array[i]);
i++;
}
for (int j = 0; j < array.length; j++) {
for (int k = j + 1; k < array.length; k++) {
if (array[k] == array[j]) {
duplicate = true;
System.out.println(array[k] + " equals " + array[j]);
break; //if duplicated found, it will exit out of the for loop
}
}
if (duplicate) {
System.out.println("we found duplicate.");
dupwin = winLoseBetDuplicate(); //if it has duplicated numbers, it will check if your numbers match up
break;
} else {
dupwin = winLostBetNonDuplicate();
}
}
return dupwin; //this will return if you have won the prize with a duplicated number. goes back to getValues
}
private boolean winLoseBetDuplicate() {
/*how this method works is we make a linked list.
use a advanced for loop and when we encounter
a hit, we remove the number from it.
if there is still a number in the linkedlist of
player number it is a lose. we still have digits as a linked list. */
//
boolean won = false;
boolean match;
for (int digitsnumbers : digits) {
System.out.println("Checking the number: " + digitsnumbers);
for (int digits2numbers : digits2) {
if (digitsnumbers == digits2numbers) {
digits.remove(digits.indexOf(digitsnumbers));
digits2.remove(digits2.indexOf(digits2numbers));
System.out.println("we found a duplicated numer match. Removing from choosing. ");
System.out.println(digits);
System.out.println(digits2);
match = true;
} else {
match = false;
}
}
}
if (digits.size() > 0) {
won = false;
} else {
won = true;
}
return won;
}
private boolean winLostBetNonDuplicate() {
boolean won;
for (int digitsnumbers : digits) {
for (int digits2numbers : digits2) {
if (digitsnumbers == digits2numbers) {
digits2.remove(digits.indexOf(digits2numbers));
digits.remove(digits.indexOf(digitsnumbers));
break;
}
}
}
if (digits.size() > 0) {
won = false;
} else {
won = true;
}
return won;
}
}

Java Binary Tree entered in a specific order

I am trying to complete an assignment where I need to write a Java program to take a string from the command line, and implement it as a Binary Tree in a specific order, then get the depth of the binary tree.
For example: "((3(4))7((5)9))"
would be entered as a tree with 7 as the root, 3 and 9 as the children, and 4 as a right child of 3, and 5 as a left child of 9.
My code is below.. The problem I am having is that, because I am basing my checks off of finding a right bracket, I am unsure how to get the elements correctly when they are not directly preceding the brackets, such as the 3 in the above string. Any direction would be greatly appreciated..
class Node {
int value;
Node left, right;
}
class BST {
public Node root;
// Add Node to Tree
public void add(int n) {
if (root == null) {
root = new Node( );
root.value = n;
}
else {
Node marker = root;
while (true) {
if (n < marker.value) {
if (marker.left == null) {
marker.left = new Node( );
marker.left.value = n;
break;
} else {
marker = marker.left;
}
} else {
if (marker.right == null) {
marker.right = new Node( );
marker.right.value = n;
break;
} else {
marker = marker.right;
}
}
}
}
} // End ADD
//Find Height of Tree
public int height(Node t) {
if (t.left == null && t.right == null) return 0;
if (t.left == null) return 1 + height(t.right);
if (t.right == null) return 1 + height(t.left);
return 1 + Math.max(height(t.left), height(t.right));
} // End HEIGHT
// Check if string contains an integer
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
} // End ISINT
public int elementCount(String[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
if (isInt(a[i])) count++;
}
return count;
}
} // End BST Class
public class Depth {
public static void main(String[] args) {
String[] a = args[0].split(" ");
BST tree = new BST();
int[] bcount = new int[10];
int[] elements = new int[10];
int x = 0, bracketcount = 0;
// Display entered string
System.out.print("Entered Format: ");
for (int j=0; j < a.length; j++) {
System.out.print(a[j]);
}
for (int i=0; i < a.length; i++) {
char c = a[i].charAt(0);
switch (c)
{
case '(':
bracketcount++;
break;
case ')':
if (isInt(a[i-1])) {
bcount[x] = bracketcount--;
elements[x++] = Integer.parseInt(a[i-1]);
}
break;
case '1':
case '7':
default : // Illegal character
if ( (a[i-1].charAt(0) == ')') && (a[i+1].charAt(0) == '(') ) {
bcount[x] = bracketcount;
elements[x++] = Integer.parseInt(a[i]);
}
break;
}
}
System.out.println("\nTotal elements: " + tree.elementCount(a));
// Display BracketCounts
for (int w = 0; w < x; w++) {
System.out.print(bcount[w] + " ");
}
System.out.println(" ");
// Display Elements Array
for (int w = 0; w < x; w++) {
System.out.print(elements[w] + " ");
}
System.out.println("\nDepth: " + tree.height(tree.root));
// Build the tree
for (int y = 0; y < x-1; y++) {
for (int z = 1; z < tree.height(tree.root); z++) {
if (bcount[y] == z) {
tree.add(elements[y]);
}
}
}
} // End Main Function
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
}
catch(NumberFormatException e) {
return false;
}
return true;
}
} // End Depth Class
I would do a couple of statements to get access to a tree with that kind of shape:
For input string : input= "((3(4))7((5)9))"
You could do :
public class Trial {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "((3(4))7((5)9))";
String easier = input.replaceAll("\\(\\(", "");
String evenEasier = easier.replaceAll("\\)\\)", "");
System.out.println(evenEasier);
int firstVal = Integer.parseInt(evenEasier.substring(0, 1));
int firstBracketVal = Integer.parseInt(evenEasier.substring(2, 3));
int middleVal = Integer.parseInt(evenEasier.substring(3, 4));
int secondBracketVal = Integer.parseInt(evenEasier.substring(4,5));
int lastVal = Integer.parseInt(evenEasier.substring(6));
System.out.println("First Val:"+firstVal);
System.out.println("First bracket Val:"+firstBracketVal);
System.out.println("Middle Val:"+middleVal);
System.out.println("Second Bracket Val:"+secondBracketVal);
System.out.println("Last Val:"+lastVal);
}
}
This however would only ever work for entries in that specific format, if that were to change, or the length of the input goes up - this would work a bit or break.....If you need to be able to handle more complicated trees as input in this format a bit more thought would be needed on how to best handle and convert into your internal format for processing.
pseudocode:
function getNode(Node)
get one char;
if (the char is "(")
getNode(Node.left);
get one char;
end if;
Node.value = Integer(the char);
get one char;
if (the char is "(")
getNode(Node.right);
get one char;
end if;
//Now the char is ")" and useless.
end function
Before calling this function, you should get a "(" first.
In this method, the framwork of a Node in string is "[leftchild or NULL] value [rightchild or NULL])".
"("is not belong to the Node, but ")" is.

Categories

Resources