For the public void setValue(int newcount) how do I make it so the value the other program sends is used to set the newcount? Also I have to do this "If the newcount < zero or > maxValue, do nothing."
private int maxValue;
private int count;
/**
* Constructor for objects of class Counter
*/
public Counter(int maxValue)
{
maxValue = 0;
}
public void decrement()
{
if (count == maxValue)
{
count = maxValue;
}
else
{
--count;
}
}
public int getValue()
{
return maxValue;
}
public void increment()
{
if (count == maxValue)
{
count = 0;
}
else
{
++count;
}
}
public void setValue(int newcount)
{
}
public String toString()
{
return "Counter{" + "maxValue=" + maxValue + '}';
}
}
I'm a little confused as to what this does:
public void decrement()
{
if (count == maxValue)
{
count = maxValue;
}
It doesn't seem to actually be decrementing the value. In fact since count == maxValue, there is no point in setting it.
This should work:
public void setValue(int newcount) {
if ((newcount < 0) || (newcount > maxValue))
return;
counter = newcount;
}
Your constructor does not do what you meant it to do:
private int maxValue;
/**
* Constructor for objects of class Counter
*/
public Counter(int maxValue)
{
maxValue = 0;
}
Your code just sets its argument to zero, the argument name hides the attribute (and why set it to 0?)
What would work, adding the #param javadoc line, is:
private int maxValue;
/**
* Constructor for objects of class Counter.
* #param newMaxValue The maximum counter value.
*/
public Counter(int newMaxValue)
{
maxValue = newMaxValue;
}
public void setValue(int newcount)
{
if(newcount >= 0 && newcount <= maxcount)
{
count = newcount;
}
}
Related
I need to initialize an Array of n Threads. Each Thread represents a number which randomly initialized in the Thread's Object creation.
The program should run m iterations. On each iteration, the Threads number needs to be updated. If both left and right neighbors in the Array are bigger than this Thread then the Thread's value will get +1 in the next iteration. If both neighbors values are lower then the Thread's value then the Thread's value will get -1. Otherwise, the Thread's value will not change.
The code starts from a code line in a GUI class. The line is:
Controller cont = new Controller(n,m)
The code enters updated method in class Controller just once and then all the Threads are going to sleep without implementing updated method.
Why is that?
This is my code:
public class Threads extends Thread
{
private int num;
private Controller cont;
private int toUpdate;
private int index;
public Threads(Controller c, int i)
{
num = (int)(Math.random() * 100 + 1); // random number between 1-100
cont = c;
index = i;
}
public void run()
{
for(int j = 1; j <= cont.getIterations(); j++)
{
toUpdate = cont.checkValue(this, this.getIndex());
cont.finished();
cont.threadWait();
num += toUpdate;
cont.updated();
cont.threadWait();
}
}
public int getValue()
{
return this.num;
}
public int getIndex()
{
return this.index;
}
}
public class Controller
{
private Threads[] threadsArray;
private int iterations;
private boolean finished = false;
private static int numOfThreads;
public Controller(int n, int m)
{
threadsArray = new Threads[n];
for(int i=0; i < threadsArray.length; i++)
threadsArray[i] = new Threads(this, i);
iterations = m;
numOfThreads = n;
printResults();
for(int i=0; i < threadsArray.length; i++)
threadsArray[i].start();
}
public synchronized void threadWait()
{
while(!finished)
{
try{ wait(); }
catch(InterruptedException e) {}
}
numOfThreads++;
waitForAll();
if(numOfThreads == threadsArray.length)
{
finished = false;
notifyAll();
}
}
public int checkValue(Threads t, int ind) //returns the thread's value to be updated. 1,-1 or 0.
public int getIterations()
{
return this.iterations;
}
public synchronized void finished()
{
numOfThreads--;
notifyAll();
if(numOfThreads == 0)
finished = true;
}
public void iteration()
{
for(int i=0; i < threadsArray.length; i++)
threadsArray[i].start();
}
public synchronized void updated()
{
numOfThreads--;
if(numOfThreads == 0)
{
printResults();
finished = true;
notifyAll();
}
}
public synchronized void waitForAll()
{
while(numOfThreads != threadsArray.length)
{
try{ wait(); }
catch(InterruptedException e) {}
}
}
public void printResults() // prints the result on each iteration.
}
I have written the code:
public int compareTo(Object w) {
//w = (Word)w
if(this.count > (Word) w.getCount()) {
return -1;
} else if (this.count < (Word) w.getCount()) {
return 1;
} else {
return 0;
}
}
I have written the class Word. It implements Comparable so I must use the Object parameter for the compareTo() method.
However, I need the object to use a method in the Word class. I get an error if I cast and was wondering if I am doing something wrong or if I need to try something else?
Word class:
package comp10152_lab3;
public class Word implements Comparable{
private int count;
private String word;
public Word(String word) {
this.word = word;
this.count = 1;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
#Override
public int compareTo(Object w) {
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
public void countUp() {
count++;
}
#Override
public String toString() {
return word + "(" + count + ")";
}
#Override
public boolean equals(Object w) {
return w.equals(word);
}
}
The equals class is suppose to be that way, as per instruction.
The error I am getting is on the w.getCount() which is a "missing symbol" error.
This is the code that you need:
public int compareTo(Object o) {
Word w = (Word) o;
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
The problem that you were having was due to the fact that w was of the type Object, the statement w = (Word) w would not do what you wanted. The second part of the problem has to do with the precedence of the cast operator in Java. When you do (Word)w.getCount(), the getCount() part gets evaluated first, meaning that you were effectively doing (Word) <some int>. What you could have done was wrap it in parentheses like ((Word) w).getCount() to solve that problem.
You should implement Comparable<Word> so that the compareTo method is public int compareTo(Word w). Also you can simplify your compareTo code:
public class Word implements Comparable<Word> {
private int count;
public int compareTo(Word w) {
return w.count - this.count;
}
}
If you can't use java generics then you can still do your compareTo in one line:
public int compareTo(Object w) {
return ((Word) w).count - this.count;
}
I am trying to create a counter that holds a number that can be increased and decreased. The program also has a boolean check: when true, the counter cannot go negative. The program seems to run fine, but I cannot get the decrease methods (both decrease by one and decrease by input) to get the boolean right. It does not check the boolean value or something? I am new to Java and need help understanding what is wrong. The class is as follows:
public class Counter {
private int value;
private boolean check;
public Counter(int startingValue, boolean check) {
if (this.check = true) {
this.value = startingValue;
if (value < 0) {
value = 0;
}
}
if (this.check = false) {
this.value = startingValue;
}
}
public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}
public Counter(boolean check) {
this.check = check;
}
public Counter() {
this.value = 0;
this.check = false;
}
public int value() {
return this.value;
}
public void increase() {
value++;
}
public void decrease() {
if (this.check == true) {
this.value--;
if (value < 0) {
value = 0;
}
} else if (this.check == false) {
this.value--;
}
}
public void increase(int IncreaseAmount) {
if (IncreaseAmount >= 0) {
this.value = value + IncreaseAmount;
}
}
public void decrease(int DecreaseAmount) {
if (DecreaseAmount >= 0) {
this.value = value - DecreaseAmount;
}
if (check == true && value < 0) {
value = 0;
}
}
}
Now, if I was to execute a main program with this class like this for example:
Counter count = new Counter (2, true);
count.decrease();
count.decrease();
count.decrease();
What I want my program to do is to not go negative since the boolean check is true. Yet it does go to -1. Why is this?
You fail to set the global variable check to false. You also used = instead of ==:
use:
public Counter(int startingValue, boolean check) {
this.check = check;
if (check == true) {
value = startingValue;
if (value < 0) {
value = 0;
}
}
else {
value = startingValue;
}
}
You need to use == to compare equality. The use of a single = sets the value.
Better yet, when checking the value of a boolean, just use the boolean. So instead of
if (someBool == true)
prefer
if (someBool)
Similarly, instead of
if (someBool == false)
prefer
if (!someBool)
Your boolean tests in your if statements need to use == for equality comparison in your constructor.
In your constructor's second if statement, you are assigning check to false.
When performing boolean logic with a boolean, just use the boolean.
So instead of
"if (this.check == true)" do "if (this.check)"
and
"if (this.check == false)" do "if (!this.check)"
Also, you had "if (this.check = true)" for some, which assigns true to this.check.
You main issue is that you missed an assignment of an method parameter to the object variable "this.check = check; // I added this"
Compare your version with this:
public class Counter {
private int value;
private boolean check;
public Counter(int startingValue, boolean check) {
this.check = check; // I added this
if (this.check) { //I changed this
this.value = startingValue;
if (value < 0) {
value = 0;
}
} else { //and this
this.value = startingValue;
}
}
public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}
public Counter(boolean check) {
this.check = check;
}
public Counter() {
this.value = 0;
this.check = false;
}
public int value() { //good practice to use getVar and setVar, ie: getValue()
return this.value;
}
public void increase() {
value++;
}
public void decrease() {
if (this.check) { // you are not consistent with this.value VS value, which can be a confusing practise
this.value--;
if (value < 0) {
value = 0;
}
} else {
this.value--;
}
}
public void increase(int increaseAmount) { //you had "IncreaseAmount", good practice to start vars with lower case
if (increaseAmount >= 0) {
this.value = + increaseAmount;
}
}
public void decrease(int decreaseAmount) {
if (decreaseAmount >= 0) {
this.value = value - decreaseAmount;
}
if (check && (value < 0)) {
value = 0;
}
}
public void print(){
System.out.println("value:"+value+" check:"+check);
}
public static void main(String[] args) {
Counter count = new Counter (2, true);
count.decrease();
count.print();
count.decrease();
count.print();
count.decrease();
count.print();
}
}
I am doing a UML and I am not quite sure how to do these mutator methods I am supposed to do this:
+turnOn(): void //sets on to true
+turnOff(): void //sets on to false
+channelUp(): void //increases channel by 1 if on, rolls to 1 after maximum
+channelDown(): void //decreases channel by 1 if on, rolls to maximum after 1
+volumeUp(): void //increases the volume by 1 if on and less than maximum
+volumeDown(): void //decreases volume by 1 if on and greater than 0
+toString( ): String //returns the current state(instance variable values)
my code right now: (keep in mind the mutator part isn't right)
public class TV {
private int volume;
private int channel;
private boolean on;
private int maxVolume;
private int maxChannel;
TV() {
volume = 1;
channel = 1;
on = false;
maxVolume = 1;
maxChannel = 1;
}
public int getChannel() {
return channel;
}
public int getVolume() {
return volume;
}
public boolean isOn() {
return on;
}
public int getMaxChannel() {
return maxChannel;
}
public int getMaxVolume() {
return maxVolume;
}
public void setChannel(int i) {
if (isOn() && i >= 1 && i <= maxChannel) channel = i;
}
public void setVolume(int i) {
if (isOn() && i >= 0 && i <= maxVolume) volume = i;
}
public void setMaxChannel(int i) {
maxChannel = i;
}
public void setMaxVolume(int i) {
maxVolume = i;
}
// + turnOn() * * This is where the mutator methods begin I need help here * *
// if (channel == maxChannel) channel = 1;
// else channel++;
//if (channel == 1) channel = max;
//else channel--;
// if (volume == maxVolume) volume = 1;
// else channel++;
//if (volume == 1) volume = max;
// else channel--;
public string toString() {
return "channel: " + channel + "\nvolume: " + volume +
"\non: " + on + "\nmax Channel: " + maxChannel +
"\nmax Volume: " + maxVolume;
}
}
Mutator generally means the same things as 'setter'
So in your above code, a 'getter' would be:
public int getMaxChannel() {
return maxChannel;
}
and a 'mutator' or 'setter' would be:
public void setMaxChannel(int maxChannel) {
this.maxChannel = maxChannel;
}
Sample methods:
public void turnOn() {
this.on = true;
}
public void channelUp() {
if (on) {
if (channel == maxChannel) {
channel = 1;
}
else {
channel++;
}
}
}
public void volumeDown() {
if (on && volume > 0) {
volume--;
}
}
Other methods follows the same logic.
Strings in java are objects, so your toString method signature should read public String toString().
We use setters and mutator as interchangeably.
A mutator method is used to set a value of a private field. It follows
a naming scheme prefixing the word "set" to the start of the method
name. These methods do not have a return type and accept a parameter
that is the same data type as their corresponding private field. The
parameter is then used to set the value of that private field.
Below are some examples of mutators or setters:
public void setMaxChannel(int i) {
maxChannel = i;
}
public void setChannel(int c) {
channel=c;
}
I have three classes, those being Lister, ObjectSortedList and SortedListProgram. I'm having trouble with the iterator for the generic class. What am I doing wrong?
This is the error I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at objectsortedlist.ObjectSortedList.getData(ObjectSortedList.java:122)
at objectsortedlist.Lister.hasNext(Lister.java:28)
at objectsortedlist.SortedListProgram.main(SortedListProgram.java:52)
Java Result: 1
Here are my classes:
package objectsortedlist;
import java.util.Iterator;
/**
*
* #author Steven
*/
public class ObjectSortedList<T> implements Cloneable, Iterable<T> {
private T[] data;
private int capacity;
public ObjectSortedList()
{
final int init_capacity = 10;
capacity = 0;
data = (T[])new Object[init_capacity];
}
public ObjectSortedList(int init_capacity)
{
if(init_capacity < 0)
throw new IllegalArgumentException("Initial capacity is negative: " + init_capacity);
capacity = 0;
data = (T[])new Object[init_capacity];
}
private boolean empty()
{
if(data.length == 0 || data[0] == null)
return true;
else
return false;
}
public int length()
{
return capacity;
}
public void insert(T element)
{
if(capacity == data.length)
{
ensureCapacity(capacity * 2 + 1);
}
data[capacity] = element;
capacity++;
}
public boolean delete(T target)
{
int index;
if(target == null)
{
index = 0;
while((index < capacity) && (data[index] != null))
index++;
}
else
{
index = 0;
while((index < capacity) && (!target.equals(data[index])))
index++;
}
if(index == capacity)
return false;
else
{
capacity--;
data[index] = data[capacity];
data[capacity] = null;
return true;
}
}
private void ensureCapacity(int minCapacity)
{
T[] placeholder;
if(data.length < minCapacity)
{
placeholder = (T[])new Object[minCapacity];
System.arraycopy(data, 0, placeholder, 0, capacity);
data = placeholder;
}
}
public ObjectSortedList<T> clone()
{
// Cloning
ObjectSortedList<T> answer;
try
{
answer = (ObjectSortedList<T>) super.clone();
}
catch(CloneNotSupportedException cnse)
{
throw new RuntimeException("This class does not implement cloneable.");
}
answer.data = data.clone();
return answer;
}
#Override
public Iterator<T> iterator()
{
return (Iterator<T>) new Lister<T>(this, 0);
}
public T getData(int index)
{
return (T)data[index];
}
}
package objectsortedlist;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
*
* #author Steven
*/
public class Lister<T> implements Iterator<T>
{
private ObjectSortedList<T> current;
private int index;
public Lister(ObjectSortedList<T> top, int index)
{
current = top;
this.index = index;
}
#Override
public boolean hasNext()
{
return (current.getData(index) == null);
}
#Override
public T next()
{
T answer;
if(!hasNext())
throw new NoSuchElementException("The Lister is empty.");
answer = current.getData(index+1);
return answer;
}
#Override
public void remove() {
throw new UnsupportedOperationException("Don't use this. Use objectsortedlist.SortedList.delete(T target).");
}
}
package objectsortedlist;
import java.util.Scanner;
/**
*
* #author Steven
*/
public class SortedListProgram {
private static Scanner scan = new Scanner(System.in);
private static String[] phraseArray = {"Hullabaloo!", "Jiggery pokery!", "Fantastic!", "Brilliant!", "Clever!", "Geronimo!", "Fish sticks and custard.", "Spoilers!",
"Exterminate!", "Delete!", "Wibbly-wobbly!", "Timey-wimey!"};
private static Lister<String> print;
public static void main(String args[])
{
int phraseNo = 0;
System.out.println("I'm gonna say some things at you, and you're going to like it."
+ " How many things would you like me to say to you? Put in an integer from 1-12, please.");
try
{
phraseNo = Integer.parseInt(scan.nextLine());
while((phraseNo < 1) || (phraseNo > 12))
{
System.out.println("The integer you entered wasn't between 1 and 12. Make it in between those numbers. Please? Pleaseeeee?");
phraseNo = Integer.parseInt(scan.nextLine());
}
}
catch(NumberFormatException nfe)
{
System.out.println("C'mon, why don't you follow directions?");
phraseNo = 0;
}
if(phraseNo == 0);
else
{
ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
for(int i = 0; i < phrases.length(); i++)
{
phrases.insert(phraseArray[i]);
}
print = new Lister<String>(phrases, phraseNo);
while(print.hasNext())
System.out.println(print.next());
}
}
}
After looking at your code I found multiple issues, here are they:
In your SortedListProgram class, in following code the phrases.length() will be 0, so the it will never go in that loop.
ObjectSortedList<String> phrases = new ObjectSortedList<String>(phraseNo);
for(int i = 0; i < phrases.length(); i++)
{
phrases.insert(phraseArray[i]);
}
Moreover in SortedListProgram class's this call sequence
print.hasNext() -> current.getData(index)
the index passed is equal to size of data array field in the
ObjectSortedList class and Since in java array indexes ranges from
zero to array size -1. So you are bound to get
java.lang.ArrayIndexOutOfBoundsException always.
Please correct your code.