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().
Related
In this problem, I am attempting to begin with an array and add or remove words. My problem so far is adding words. I want to have an array String[] {"",""} and fill this up, and if a word is repeated, do nothing. So, add("computer"), add("again"), and add("computer") would result in {"computer", "again"} and give me count 3. I keep getting {"computer", "computer", "again"} remove("computer") would result in {"again", "again"} and give me count 1. Could on look at this code and help?
public class WordList {
public String[] words;
int count;
public WordList() {
count = 0;
words = new String[] {"",""};
}
public int addWord(String w) {
WordList r = new WordList();
int x = r.findWord(w);
int y = words.length;
if (x>-1) {
return count;
}
else if (x==-1) {
if (count < words.length) {
words[count] = w;
}
else if (count == words.length) {
String[] nwords = new String[words.length * 2];
for (int i = 0; i < words.length; i++) {
nwords[i] = words[i];
}
words = nwords;
words[y] = w;
}
count++;
}
return count;
}
public void removeWord(String s) {
WordList r = new WordList();
int x = r.findWord(s);
if (x == -1) {
return;
}
if (x>-1) {
for (int j=0;j<words.length;j++) {
words[j] = words[j+1];
count--;
}
}
return;
}
public int findWord(String w) {
for (int i =0;i<words.length; i++) {
if (w.equals(words[i])) {
return i;
}
}
return -1;
}
public boolean equals(WordList other) {
if (words.length != other.count) {
return false;
} else {
for (int i = 0; i < words.length; i++) {
if (words[i] != other.words[i]) {
return false;
}
}
}
return true;
}
public String toString() {
String s = "There are " + count + " word" + ((words.length == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl.addWord("abacus"));
System.out.println(wl.addWord("computer"));
wl.removeWord("computer");
}
}
First of all. Please consider Arraylist or Map.
Nevertheless i tried to keep changes to the minimal
public class WordList {
public String[] words;
int count;
public WordList() {
count = 0;
words = new String[] {"",""};
}
public int addWord(String w) {
//WordList r = new WordList();
int x = findWord(w);
int y = words.length;
if (x>-1) {
return count++;
}
else if (x==-1) {
if (count < words.length) {
words[count] = w;
}
else if (count == words.length) {
String[] nwords = new String[words.length * 2];
for (int i = 0; i < words.length; i++) {
nwords[i] = words[i];
}
words = nwords;
words[y] = w;
}
count++;
}
return count;
}
public void removeWord(String s) {
//WordList r = new WordList();
int x = findWord(s);
if (x == -1) {
return;
}
if (x>-1) {
for (int j=0;j<words.length;j++) {
if(words.length < j+1 && !words[j+1].isBlank()){
words[j] = words[j+1];
}
}
count--;
}
return;
}
public int findWord(String w) {
for (int i =0;i<words.length; i++) {
if (w.equals(words[i])) {
return i;
}
}
return -1;
}
public boolean equals(WordList other) {
if (words.length != other.count) {
return false;
} else {
for (int i = 0; i < words.length; i++) {
if (words[i] != other.words[i]) {
return false;
}
}
}
return true;
}
public String toString() {
String s = "There are " + count + " word" + ((words.length == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl);
System.out.println(wl.addWord("abacus"));
System.out.println(wl);
System.out.println(wl.addWord("computer"));
System.out.println(wl);
wl.removeWord("computer");
System.out.println(wl);
}
}
The severe ones are:
1. You are working on new instances of wordlist (r) when adding and removing which is absolutely wrong.
2. When removing word you have to check the length of word before going for j+1
You should use a Set, not an array.
That will reduce your code to:
class WordList {
private Set<String> words;
public WordList() {
words = new HashSet<>();
}
public int addWord(String w) {
words.add(w);
return words.size();
}
public void removeWord(String s) {
words.remove(s);
}
public boolean findWord(String w) {
return words.contains(w);
}
public boolean equals(WordList other) {
return this.words.equals(other.words);
}
#Override
public String toString() {
String s = "There are " + words.size() + " word" + ((words.size() == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl.addWord("abacus"));
System.out.println(wl.addWord("computer"));
wl.removeWord("computer");
}
}
Output
1
2
2
I need to create an ID based on a 15x15 matrix values and since it is not possible to create an integer of size 15, I tried the following reasoning to create an ID of type double:
First I create a String with the values of the cells and while I do this, I look for the cell that has a value of 0. When I find I enter a dot "." in the String. Then I convert my String to BigDecilmal and the method I call doubleValue ().
public double generateId() {
String sid = "";
for (int i = 0; i < this.matrix[0].length; i++) {
for (int j = 0; j < matrix[1].length; j++) {
if (matrix[i][j].equals("0")) {
sid += ".";
} else {
sid += matrix[i][j];
}
}
}
System.out.println("ID: " + new BigDecimal(sid).doubleValue());
return new BigDecimal(sid).doubleValue();
}
I checked and the generated IDs are uniques.
Based on this, I tried to implement HashCode() as follows:
#Override
public int hashCode() {
long bits = doubleToLongBits(id);
int hash = (int) (bits ^ (bits >>> 32));
System.out.println("hash: " + hash);
return hash;
}
But my HashSet continues with duplicate values :(
Does anyone have a suggestion about how to do this?
~~>EDIT
Sate class:
public class State {
public double id;
public String[][] matrix;
public State() {
}
public State(String[][] matrix) {
this.matrix = createMatrix(matrix);//is created from a existing matrix
this.id = generateId();
}
#Override
public boolean equals(Object other) {
if ((other == null) || !(other instanceof State)) {
return false;
}
return ((State) other).getId().equals(this.getId()) && ((State) other).getId() == this.getId();
}
#Override
public int hashCode() {
long bits = doubleToLongBits(id);
int hash = (int) (bits ^ (bits >>> 32));
System.out.println("hash: " + hash);
return hash;
}
public String toString() {
return "Hashcode: " + this.hashCode();
}
public Double getId() {
return id;
}
public void setId(Double id) {
this.id = id;
}
public String[][] getMatrix() {
return matrix;
}
public void setMatrix(String[][] matrix) {
this.matrix = matrix;
}
public double generateId() {
String sid = "";
for (int i = 0; i < this.matrix[0].length; i++) {
for (int j = 0; j < matrix[1].length; j++) {
if (matrix[i][j].equals("0")) {
sid += ".";
} else {
sid += matrix[i][j];
}
}
}
System.out.println("ID: " + new BigDecimal(sid).doubleValue());
return new BigDecimal(sid).doubleValue();
}
private String[][] createMatrix(String[][] matriz) {
String[][] copia = new String[matriz[0].length][matriz[1].length];
for (int i = 0; i < copia[0].length; i++) {
for (int j = 0; j < copia[1].length; j++) {
copia[i][j] = matriz[i][j];
}
}
return copia;
}
your problem is in the equals method,
you have to remove the last part:
&& ((State) other).getId() == this.getId();
you are checking if the Boolean has the same reference, but they don't need the reference to be equal, it's enough that there value is equal
I would propose using the built-in methods of the Arrays class to generate a hashCode and test for equality:
#Override
public int hashCode() {
return Arrays.deepHashCode(matrix);
}
#Override
public boolean equals(Object other) {
if ((other == null) || !(other instanceof State)) {
return false;
}
State s = (State)other;
return Arrays.deepEquals(matrix, s.matrix);
}
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
I am having trouble for the past week trying to solve how to check if an Id has already been added to the array, and if it has, stop the user from entering the rest of the data, I would greatly appreciate some help with this.
My code:
class CustomerUse {
public static int checkId(Customer theArray[], int noOfValues,
String searchId) {
int idCheck = 0;
int step = 0;
while (step < noOfValues) {
step++;
if ((step < noOfValues) && (theArray[step].getId().equals(searchId))) {
idCheck = -1;
}
}
return idCheck;
}
public static void listAllNames(Customer[] names, int NoOfElements) {
int index;
String result;
for (index = 0; index < NoOfElements; index++) {
System.out.println(names[index]);
}
}
public static int findPlace(Customer theArray[], int balance, int noOfValues) {
int step;
int place;
step = 0;
while ((step < noOfValues) && (balance < theArray[step].getBalance())) {
step++;
}
place = step;
return place;
}
public static int addOne(Customer theArray[], int place, String Id,
Customer theObject, int noOfValues) {
int step;
if (noOfValues == 0) {
theArray[0] = theObject;
noOfValues++;
} else {
for (step = noOfValues - 1; step >= place; step--) {
theArray[step + 1] = theArray[step];
}
theArray[place] = theObject;
noOfValues++;
}
return noOfValues;
}
public static int deleteName(Customer theArray[], int noOfElements) {
String searchId;
int step;
int whichOne = 0;
System.out.println("Enter Id of customer to be deleted ");
searchId = EasyIn.getString();
step = 0;
while ((step < noOfElements)
&& !(theArray[step].getId().equals(searchId))) {
step++;
}
if (step < noOfElements) {
whichOne = step;
for (step = whichOne; step < noOfElements - 1; step++) {
theArray[step] = theArray[step + 1];
}
noOfElements--;
} else {
System.out.println(" Sorry this customer doesn't exist");
}
return noOfElements;
}
public static void main(String[] args) {
Customer empArray[];
int index;
int noOfElements;
String searchName;
Customer tempObject;
int step;
int option = 0;
int place;
String newName = "";
String newId;
int newBalance;
int checkID = 0;
empArray = new Customer[100000];
noOfElements = 0;
System.out
.println("\n 1. Add Customer \n 2. Delete Customer \n 3. List all Customers \n 4. Exit");
System.out.print("Enter Option ");
option = EasyIn.getInt();
while (option != 4) {
if (option == 1) {
System.out.print("Enter ID ");
newId = EasyIn.getString();
System.out.print("Enter name ");
newName = EasyIn.getString();
System.out.print("Enter Balance ");
newBalance = EasyIn.getInt();
System.out.println();
tempObject = new Customer(newName, newId, newBalance);
place = findPlace(empArray, newBalance, noOfElements);
noOfElements = addOne(empArray, place, newId, tempObject,
noOfElements);
checkID = checkId(empArray, noOfElements, newId);
if (checkID == -1) {
System.out.println("Sorry this ID already exists");
checkID = 0;
}
} else if (option == 2) {
noOfElements = deleteName(empArray, noOfElements);
} else if (option == 3) {
listAllNames(empArray, noOfElements);
}
System.out.print("Enter Option ");
option = EasyIn.getInt();
}
}
}
This effectively skips array entry at index 0:
while (step < noOfValues)
{
step++;
Better:
public static int checkId(Customer theArray[], int noOfValues, String searchId){
for (int step = 0; step < noOfValues; ++step ){
if( theArray[step].getId().equals(searchId) )
{
return step;
}
}
return -1;
}
Return -1 on not found, otherwise the index.
I haven't checked the remainder of your code, just saw that the use of an array should be discarded in favour of a List.
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