need quick help in Java Program Lab - java

i have a lab for my java class. I have everything except cannot get the average method to work properly. Whenever i run the program, the average is calculated from the random values and not the one updated.
package ArrayKeyAccess;
/**
* Class Definition for Data Element
* Minimal Definition -- No Error Checking
* Instructional Model -- Conceptual Emphasis
*/
public class Data
{
private int studentID;
private int test1;
private int test2;
private int test3;
private int average;
private String letterGrade;
private static int nextSID = 99; //cheap sequence number approach
private static int getNextSID()
{
return ++nextSID;
}//getNextKey
public Data(int n) //no error checking
{
this.setStudentID(getNextSID());
this.setTest1(n);
this.setTest2(n);
this.setTest3(n);
}//Data constructor
public Data(int k, int n) //no uniqueness checking
{
this.setStudentID(k);
this.setTest1(n);
this.setTest2(n);
this.setTest3(n);
}//Data constructor
public Data( Data d ) //Copy Constructor
{ //required for Composition
this.setStudentID(d.getStudentID());
this.setTest1(d.getTest1());
this.setTest2(d.getTest2());
this.setTest3(d.getTest3());
this.calculateAverage(getTest1(), getTest2(), getTest3());
this.determineLetterGrade(letterGrade);
}//copy constructor
public Data copy() //Copy Object
{ //required for Compostion
return new Data(this);
}//copy object
public String toString()
{
return "Student ID: " + this.getStudentID() + '\n' +
"Test 1: " + this.getTest1() + '\n' +
"Test 2: " + this.getTest2() + '\n' +
"Test 3: " + this.getTest3() + '\n' +
"Average: " + this.getAverage() + '\n' +
"Letter Grade: " + this.getLetterGrade() + '\n';
}//toString
public void setStudentID (int n) //no error checking
{
studentID = n;
}
public int getStudentID()
{
return studentID;
}
//----------------------Test1---------------------------------------
public void setTest1(int n) //no validity checking
{
test1 = n;
}
public int getTest1()
{
return test1;
}
//----------------------Test2---------------------------------------
public void setTest2(int n) //no validity checking
{
test2 = n;
}
public int getTest2()
{
return test2;
}
//----------------------Test3---------------------------------------
public void setTest3(int n) //no validity checking
{
test3 = n;
}
public int getTest3()
{
return test3;
}
//---------------calculate average score-----------------------------
public void calculateAverage(int test1, int test2, int test3) //set
{
this.test1 = getTest1();
average = (getTest1() + getTest1() + getTest3()) / 3;
}
//----------------determine letter grade------------------------------
public void determineLetterGrade(String letterGrade)
{
if(average >= 90)
letterGrade = "A";
else if(average >= 80)
letterGrade = "B";
else if(average >= 70)
letterGrade = "C";
else if(average >= 60)
letterGrade = "D";
else
letterGrade = "F";
this.letterGrade = letterGrade;
}
//getAverageScore
public int getAverage() //get
{
return average;
}
//getLetterGrade
public String getLetterGrade()
{
return letterGrade;
}
}//class Data
ProgramTest
UnsortedArray s = new UnsortedArray(10);
int score;
//add 10 data elements
for( int i=1; i<=10; i++ )
{
score = 50 + (int)(Math.random()*50)+1;
s.insert( new Data(score) );
}
System.out.println("------------------TEST 1----------------------");
//update test 1
s.updateTest1(100,44);
s.updateTest1(101,89);
s.updateTest1(102,80);
s.updateTest1(103,95);
s.updateTest1(104,65);
s.updateTest1(105,74);
s.updateTest1(106,69);
s.updateTest1(107,56);
s.updateTest1(108,88);
s.updateTest1(109,99);
s.showList();
The Unsorted Array Class ( i forgot to attach before)
package ArrayKeyAccess;
/**
* Class Definition for Unsorted Array
* Minimal Basic Methods
* Implements Insert, Fetch, Update, Delete
* Conceptual Instructional Model
*/
public class UnsortedArray
{
private int next; //next insert position
private int size; //array capacity
private Data[] a; //reference for container of
//data elements
public UnsortedArray(int n) //no error checking
{
next = 0;
size = n;
a = new Data[size];
}//constructor
public boolean insert( Data newNode )
{
if( next >= size ) //array is full
return false;
//insert copy in next position
a[next] = new Data( newNode );
++next;
return true;
}//insert
public Data fetch( int targetKey )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return null;
else //node was found
return a[i].copy(); //return a copy
}//fetch
//Update data element field in the container
public boolean updateTest1( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest1( val );
return true;
}
}//updateTest1
public boolean updateTest2( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest2( val );
return true;
}
}//updateTest2
public boolean updateTest3( int targetKey, int val )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i].setTest3( val );
return true;
}
}//updateTest1
//overload update method
//assumes record was fetched and
//value was modified and now is
//to be "reinserted".
public boolean update( int targetKey, Data updNode )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i] = updNode.copy(); //assign copy
return true; //preserve Composition
}
}//update
public boolean delete( int targetKey )
{
int i=0;
while( i!=next && a[i].getStudentID()!=targetKey ) ++i;
if( i==next ) //node not found
return false;
else //node was found
{
a[i] = a[next-1]; //move last node to deleted position
//"deleted" node has no reference
a[next-1] = null; //new next available position
--next; //reset insert position
return true;
}
}//delete
public void showList() //List the nodes
{
for(int i=0; i<next; i++)
System.out.println( a[i] );
}//showList
}//class UnsortedArray

Well, there's two problems.
First, you're adding getTest1() twice. That's worth fixing in its own right.
The second problem is that you're going to run into integer division - simply because all four of your values are going to be ints, you won't get any floating-point values (or a "true" average).
What you want to do is change the type of average to double, then change your divdend into a floating point number, as such:
average = (getTest1() + getTest2() + getTest3()) / 3.0;

It may be because you add test1 twice.
average = (getTest1() + getTest1() + getTest3()) / 3;

i figured it out, these are my changes, no getters for calculateAverage or letterGrade
public int calculateAverage() //set
{
average = (this.getTest1() + this.getTest2() + this.getTest3()) / 3;
return average;
}
public String letterGrade()
{
if(this.average >= 90)
letterGrade = "A";
else if(this.average >= 80)
letterGrade = "B";
else if(this.average >= 70)
letterGrade = "C";
else if(this.average >= 60)
letterGrade = "D";
else
letterGrade = "F";
return letterGrade;
}
public String toString()
{
return "Student ID: " + this.getStudentID() + '\n' +
"Test 1: " + this.getTest1() + '\n' +
"Test 2: " + this.getTest2() + '\n' +
"Test 3: " + this.getTest3() + '\n' +
"Average: " + calculateAverage() + '\n' +
"Letter Grade: " + this.letterGrade() + '\n';
}//toString

Related

Autocomplete byReverseWeightOrder comparator issue

I have been working on this problem for several hours now and I just cannot figure out what I am doing wrong here. Could anyone help point me in the right direction?
I was asked to write an Autocomplete program and I've completed everything except for this one method I cannot get working. Each term has: 1. String query and 2. long weight.
Here is the method:
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() { // LINE CAUSING PROBLEM
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) { // LINE CAUSING PROBLEM
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
My problem is that no matter how I mess with the method I always result in a NullPointerException(). Which, it points to this method (byReverseWeightOrder) as well as these two statements.
Arrays.sort(matches, Term.byReverseWeightOrder());
Term[] results = autocomplete.allMatches(prefix);
Here is the rest of the code if it can be found helpful:
Term
import java.util.Comparator;
public class Term implements Comparable<Term> {
public String query;
public long weight;
public Term(String query, long weight) {
if (query == null) {
throw new java.lang.NullPointerException("Query cannot be null");
}
if (weight < 0) {
throw new java.lang.IllegalArgumentException("Weight cannot be negative");
}
this.query = query;
this.weight = weight;
}
public static Comparator<Term> byReverseWeightOrder() {
return new Comparator<Term>() {
public int compare(Term t1, Term t2) {
if (t1.weight > t2.weight) {
return -1;
} else if (t1.weight == t2.weight) {
return 0;
} else {
return 1;
}
}
};
}
public static Comparator<Term> byPrefixOrder(int r) {
if (r < 0) {
throw new java.lang.IllegalArgumentException("Cannot order with negative number of characters");
}
final int ref = r;
return
new Comparator<Term>() {
public int compare(Term t1, Term t2) {
String q1 = t1.query;
String q2 = t2.query;
int min;
if (q1.length() < q2.length()) {
min = q1.length();
}
else {
min = q2.length();
}
if (min >= ref) {
return q1.substring(0, ref).compareTo(q2.substring(0, ref));
}
else if (q1.substring(0, min).compareTo(q2.substring(0, min)) == 0) {
if (q1.length() == min) {
return -1;
}
else {
return 1;
}
}
else {
return q1.substring(0, min).compareTo(q2.substring(0, min));
}
}
};
}
public int compareTo(Term that) {
String q1 = this.query;
String q2 = that.query;
return q1.compareTo(q2);
}
public long getWeight() {
return this.weight;
}
public String toString() {
return this.weight + "\t" + this.query;
}
}
BinarySearchDeluxe
import java.lang.*;
import java.util.*;
import java.util.Comparator;
public class BinarySearchDeluxe {
public static <Key> int firstIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) <= 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
return -1;
}
public static <Key> int lastIndexOf(Key[] a, Key key, Comparator<Key> comparator) {
if (a == null || key == null || comparator == null) {
throw new java.lang.NullPointerException();
}
if (a == null || a.length == 0) {
return -1;
}
int left = 0;
int right = a.length - 1;
while (left + 1 < right) {
int middle = left + (right - left)/2;
if (comparator.compare(key, a[middle]) < 0) {
right = middle;
} else {
left = middle;
}
}
if (comparator.compare(key, a[right]) == 0) {
return right;
}
if (comparator.compare(key, a[left]) == 0) {
return left;
}
return -1;
}
}
AutoComplete
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
public class Autocomplete {
public Term[] terms;
public Autocomplete(Term[] terms) {
if (terms == null) {
throw new java.lang.NullPointerException();
}
this.terms = terms.clone();
Arrays.sort(this.terms);
}
public Term[] allMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int count = start;
System.out.println("Start: " + start + " End: " + end);
if (start == -1 || end == -1) {
// System.out.println("PREFIX: " + prefix);
throw new java.lang.NullPointerException();
} // Needed?
Term[] matches = new Term[end - start + 1];
//matches = Arrays.copyOfRange(terms, start, end);
for (int i = 0; i < end - start; i++) {
matches[i] = this.terms[count];
count++;
}
Arrays.sort(matches, Term.byReverseWeightOrder());
System.out.println("Finished allmatches");
return matches;
}
public int numberOfMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException();
}
Term theTerm = new Term(prefix, 0);
int start = BinarySearchDeluxe.firstIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
int end = BinarySearchDeluxe.lastIndexOf(terms, theTerm, Term.byPrefixOrder(prefix.length()));
System.out.println("Finished numberMatches");
return end - start + 1; // +1 needed?
}
public static void main(String[] args) throws IOException {
// Read the terms from the file
Scanner in = new Scanner(new File("wiktionary.txt"));
int N = in.nextInt(); // Number of terms in file
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.nextLong(); // read the next weight
String query = in.nextLine(); // read the next query
terms[i] = new Term(query.replaceFirst("\t",""), weight); // construct the term
}
Scanner ip = new Scanner(System.in);
// TO DO: Data Validation Here
int k;
do {
System.out.println("Enter how many matching terms do you want to see:");
k = ip.nextInt();
} while (k < 1 || k > N);
Autocomplete autocomplete = new Autocomplete(terms);
// TO DO: Keep asking the user to enter the prefix and show results till user quits
boolean cont = true;
do {
// Read in queries from standard input and print out the top k matching terms
System.out.println("Enter the term you are searching for. Enter * to exit");
String prefix = ip.next();
if (prefix.equals("*")) {
cont = false;
break;
}
Term[] results = autocomplete.allMatches(prefix);
System.out.println(results.length);
for(int i = 0; i < Math.min(k,results.length); i++)
System.out.println(results[i].toString());
} while(cont);
System.out.println("Done!");
}
}
I apologize for the sloppy code, I have been pulling my hair out for awhile now and keep forgetting to clean it up.
Two examples:
Example 1:
int k = 2;
String prefix = "auto";
Enter how many matching terms do you want to see:
2
Enter the term you are searching for. Enter * to exit
auto
619695 automobile
424997 automatic
Example 2:
int k = 5;
String prefix = "the";
Enter how many matching terms do you want to see:
5
Enter the term you are searching for. Enter * to exit
the
5627187200 the
334039800 they
282026500 their
250991700 them
196120000 there

CircularQueue Test errors, indent

Here's my code below. I'm new to java. The line in my test is getting an error. The line
x = Response.char At(0); is expecting an identifier?
import java.util.Scanner;
public class CircularQueue {
private int head, tail;
private String [ ] q = new String [ 10 ];
private String name;
int Size;
Scanner input = new Scanner (System.in);
public CircularQueue () {
head = -1;
tail = -1;
}
public void insertQueue () {
if (isQueueFull () )
System.out.println ("Overflow");
else {
name = getName ();
if (isQueueEmpty () )
head = +1;
if (tail==Size-1)
tail=-1;
q [++ tail] = name;
}
}
public void deleteQueue() {
String x;
if ( isQueueEmpty () )
System.out.println("Underflow");
else {
x=q[head];
System.out.println ("Servicing " + x);
if (head==tail) {
head=-1;
tail=-1;
}
else {
head ++;
if (head==Size)
head=0;
}
}
}
public void setSize(int i)
{
Size=i;
}
private String getName () {
System.out.println("Enter name");
return input.nextLine ();
}
public boolean isQueueEmpty () {
return (head==-1);
}
public boolean isQueueFull () {
return ((tail-head+1==0) || (tail-head+1==Size));
}
public void printQueueLogical () {
int next;
if (isQueueEmpty())
System.out.println ("Empty");
else {
next=head;
System.out.println (" q [" + next + "] = " +q[next]);
while (next != tail) {
next ++;
if (next==Size)
next=0;
System.out.println (" q [" + next + "] = " +q[next]);
}
}
}
public void printQueuePhysical () {
for (int J=0; J<Size; J++)
System.out.println (" q [" + J + "]= " + q [J]);
}
}
class TestCircularQueue2 {
public static void main ( String [] args) {
CircularQueue n = new CircularQueue ();
Scanner in = new Scanner (System.in);
String Response;
char x;
System.out.println("Enter command - i/d/l/p/q");
Response = in.next ();
x = Response.char At(0);
x = character.toLowerCase (x);
while (x != 'q' && x != 'Q') {
switch (x) {
case 'i':
n.insertQueue ();
break;
case 'd':
n.deleteQueue();
break;
case 'l':
n.printQueueLogical();
break;
case 'y':
n.printQueuePhysical();
break;
default:
System.out.println ("Illegal Response");
break;
}
System.out.println ("enter command - i/d/l/p/q");
Response = in.next ();
x = Response.char At(0);
x = character.toLowerCase (x);
}
}
}
The method is charAt() not char At(), so you should change the lines
x = Response.char At(0);
to
x = Response.charAt(0);
Also, note that the class is Character not character, so you should use:
Character.toLowerCase(x)
Note: Try to follow Java naming conventions. Use names like someVar for variables/methods and use names like SomeClass for classes.

Very Basic Java: For-Loop in Java method won't run

I've never asked a question on this before but I'd appreciate any help anyone can provide. I'm currently learning the fundamentals of Java so this is more than likely a very basic problem. When I call this method, nothing seems to happen and I can't figure out why. I could just change it to type void and use system.print but I'd rather not, anyhow here's the code:
public double calcTotal()
{
double total = 0.00;
for (int i = 0; i < jSongs.size(); i++)
{
total += jSongs.get(i).getPrice();
}
return total;
}
I think it would be easier if I just showed you guys the whole lot, this is the app that's calling the methods to test them:
public class JukeboxApp {
public static void main(String[] args) {
Song s1 = new Song("Metallica", "The Unforgiven", 1.25, 6.23);
Song s2 = new Song("Test Artist 2", "Test Title 2", 4.00, 3.40);
Song s3 = new Song("Test Artist 3", "Test Title 3", 6.00, 2.50);
Jukebox jb = new Jukebox();
jb.addSong(s1);
jb.addSong(s2);
jb.addSong(s3);
jb.displaySongs();
jb.removeSong("The Unforgiven");
jb.searchSong("Test Title 2");
jb.calcTotal();
}
}
Here is the jukebox class, which I'm sure is full of mistakes:
import java.util.ArrayList;
public class Jukebox {
private String name;
private ArrayList<Song> jSongs;
public Jukebox()
{
name = "Primary Jukebox";
jSongs = new ArrayList<Song>();
}
public String getName()
{
return name;
}
public double calcTotal()
{
double total = 0.00;
for (int i = 0; i < jSongs.size(); i++)
{
total += jSongs.get(i).getPrice();
}
return total;
}
public void searchSong(String sTitle)
{
boolean check = false;
if ( jSongs.size() == 0 ) {
System.out.println("The are no songs in the list.");
check = true;
} else if ( jSongs.size() != 0 ) {
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getTitle().equals(sTitle) == true ) {
check = true;
System.out.println(jSongs.get(i));
}
}
}
if ( check == false ) {
System.out.println("The searched song could not be found.");
}
}
public String searchArtist(String sArtist)
{
int countMatch = 0;
for (int i = 0; i < jSongs.size(); i++) {
if ( jSongs.get(i).getArtist().equals(sArtist) ) {
countMatch++;
return jSongs.get(i).getTitle();
} else if ( countMatch == 0 ) {
return "The requested artist could not be found.";
}
}
return "If you would like to search for another artist, please enter the corresponding number.";
}
public void addSong(Song s1)
{
boolean check = false;
if ( jSongs.size() == 0 ) {
System.out.println("Your song will be added to the list.");
jSongs.add(s1);
return;
} else if ( jSongs.size() != 0 ) {
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i) == s1 ) {
check = true;
}
}
}
if ( check == false ) {
System.out.println("Your song will be added to the list.");
jSongs.add(s1);
} else if ( check == true ) {
System.out.println("Your song is already in the list.");
}
}
public void removeSong(String title)
{
boolean check = false;
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getTitle().equals(title) ) {
jSongs.remove(i);
check = true;
}
}
System.out.println(check);
}
public void displaySongs()
{
for ( int i = 0; i < jSongs.size(); i++ ) {
System.out.println(jSongs.get(i));
}
}
public Song showMostExpensive()
{
double price = 0.00;
Song mostESong = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getPrice() > price ) {
price = jSongs.get(i).getPrice();
mostESong = jSongs.get(i);
}
}
return mostESong;
}
public Song showShortest()
{
double length = 500.00;
Song shortest = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getLength() < length ) {
length = jSongs.get(i).getLength();
shortest = jSongs.get(i);
}
}
return shortest;
}
public Song mostPlayed()
{
int count = 0;
Song mostPSong = new Song();
for ( int i = 0; i < jSongs.size(); i++ ) {
if ( jSongs.get(i).getCount() > count ) {
count = jSongs.get(i).getCount();
mostPSong = jSongs.get(i);
}
}
return mostPSong;
}
}
And here is the class that creates the song objects:
public class Song {
private String artist;
private String title;
private double price;
private int playCount;
private double length;
public Song()
{
artist = "unknown";
title = "unknown";
price = 0.00;
length = 0.00;
playCount = 0;
}
public Song(String artist, String title, double price, double length)
{
this.artist = artist;
this.title = title;
this.price = price;
this.length = length;
playCount = 0;
}
public String getArtist()
{
return artist;
}
public String getTitle()
{
return title;
}
public double getPrice()
{
return price;
}
public int getCount()
{
return playCount;
}
public double getLength()
{
return length;
}
public void changePrice(double newPrice)
{
price = newPrice;
}
public void playSong()
{
playCount++;
System.out.println(title + " is now playing." + "\n" + toString());
}
public String toString()
{
return artist + "\n"
+ title + "\n"
+ price + "\n"
+ length;
}
}
Your description makes me think that you are calling your method like so
calcTotal();
instead of actually using the value returned by the method
double total = calcTotal();
System.out.println(total);
Your code seem to be good. Probably the function for addSong could be easier. But the problem is that you're not printing the result of the function calcTotal().

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.

Adding duplicates in an ArrayList

I am stuck on how to find duplicate entries in an ArrayList and then manipulate them. I am implementing a polynomial class and I want to add monomials of the same order to create a new polynomial. Monomials have a degree and a coefficient. I want to cycle through a collection of monomials and find the monomials that have the same power and add the coefficients. The sum of all these like powered monomials will be the polynomial.
ArrayList (or any List) accepts duplicates.
However, since you want to group Monomials by their power, you might consider using a Map<Integer,Foo> where the key is the power. Foo has a lot of options. Foo could be an ArrayList<Monomial>, an ArrayList<Double>, holding only the coefficiants, that you add later. This requires some code writing on your part or else using a 3rd partly library for a MultiMap.
Or, Foo could be a Double which represents the summed coefficient, in which case you need to write an add(Monomial) method which updates the Double everytime.
If the possible range of powers is small and known, you could use a simple array too.
Here's my solution, you can add two polynomials of the same degree. Watch for bugs.
public class Polynome {
private double[] coefficients;
private int degre;
public Polynome(int degre) {
if (degre < 0) {
System.out.println("Invalid Degree");
}
this.degre = degre;
coefficients = new double[degre + 1];
for (int i = 0; i < degre; i++)
coefficients[i] = 0;
coefficients[degre] = 1;
}
public void setCoefficient(int degre, double coefficient) {
if (degre < 0 || degre > this.degre) {
System.out.println("Invalid Degree");
}
if (coefficient == 0 && degre == this.degre && this.degre != 0) {
System.out.println("Null Degree");
}
coefficients[degre] = coefficient;
}
/*
* Returns the coeff giving the degree of the element
*/
public double getCoefficient(int degre) {
if (degre < 0 || degre > this.degre) {
return 0;
}
if (degre == this.degre && this.degre != 0) {
return coefficients[this.getDegre()];
}
return this.coefficients[degre];
}
public String ToString() {
if (degre == 0)
return "" + this.coefficients[0];
String result = "" + this.coefficients[degre]+" x^" + degre;
for (int i = degre-1 ; i > 0 ; i--){
if (this.coefficients[i] < 0) {
result += "-" + Math.abs(this.coefficients[i]) + " x^" + i;
}
else {
if (this.coefficients[i] > 0){
result += " + " + this.coefficients[i] + " x^" + i;
}
}
}
if (this.coefficients[0]!= 0) result += " + " + this.coefficients[0] ;
return result;
}
/*
* Returns the degree of the current poly
*/
public int getDegre() {
return degre;
}
/*
* Adds two Polys with the same degrees
*/
public Polynome add(Polynome p) {
Polynome result = new Polynome(p.getDegre());
int deg = result.getDegre();
for(int i = deg ; i >0 ; i--) {
result.coefficients[i] = this.getCoefficient(i) + p.getCoefficient(i);
}
return result;
}
public static void main(String...args) {
Polynome p = new Polynome(2);
p.setCoefficient(2, 7);
Polynome p1 = new Polynome(2);
p1.setCoefficient(2, 2);
System.out.println(p.ToString() + "\n" + p1.ToString() + "\n\n" + (p.add(p1)).ToString());
}
}

Categories

Resources