Beginner here, programming a simple counter to have a limit? - java

Here is my counter class.
public class Counter {
private int value;
public int getValue() {
return value;
}
public void click() {
value = value + 1;
}
public void unclick() {
value = value - 1;
}
public void reset() {
value = 0;
}
public void setLimit(int maximun) {
maximun = 10;
}
}
and here is my tester
public class counterDemo {
public static void main(String[] args) {
Counter tally = new Counter();
tally.click();
tally.click();
tally.click();
tally.click();
tally.click();
tally.click();
tally.click();
tally.click();
tally.click();
tally.click();
tally.click();
int result = tally.getValue();
System.out.println("results: " + result);
}
}
I'm asked to use math.min(n, limit) to make it so if the click is used more often than limit, it has no effect. Could anyone help me? This seems really simple but I haven't seen something like this used and cant figure it out. Thanks

Math.min, returns a value.
you should use it like this.
public void click()
{
value = Math.min(10, value + 1);
}
or if you want to use that variable...
public void click()
{
value = Math.min(maximun, value + 1);
}
just make sure that you have a maximun as an instance variable of counter
public class Counter {
private int value;
private int maximun;
public void setLimit(int maximun) {
this.maximun = maximun;
}
}

Related

Is final variable changing its value throughout time?

I'm currently teaching myself Java from a textbook, and found a piece of code that I don't understand - why does the final variable id change it's value?
import static net.mindview.util.Print.*;
class Shared {
private int refcount = 0;
private static int counter = 0;
private final int id = counter++;
public Shared() {
print("Creating " + this);
}
public void addRef() { refcount++; }
protected void dispose() {
if(--refcount == 0)
print("Disposing " + this);
}
protected void finalize() {
if(refcount != 0)
print("Error: object is not properly cleaned-up!");
}
public String toString() { return "Shared " + id; }
}
class Composing {
private Shared shared;
private static int counter = 0;
private final int id = counter++;
public Composing(Shared shared) {
print("Creating " + this);
this.shared = shared;
this.shared.addRef();
}
protected void dispose() {
print("disposing " + this);
shared.dispose();
}
public String toString() { return "Composing " + id; }
}
public class E13_VerifiedRefCounting {
public static void main(String[] args) {
Shared shared = new Shared();
Composing[] composing = { new Composing(shared),
new Composing(shared), new Composing(shared),
new Composing(shared), new Composing(shared) };
for(Composing c : composing)
c.dispose();
This:
private static int counter = 0;
private final int id = counter++;
public Shared() {
print("Creating " + this);
}
is the same as this:
private static int counter = 0;
private final int id;
public Shared() {
id = counter++;
print("Creating " + this);
}
That is, the id is assigned every time the constructor executes, with the side effect that counter is incremented.
id is an instance variable, so each instance of shared gets its own id value.
private final int id = counter++;
If by change you are asking why does the value of id is counter + 1 instead of just counter, that's because first the sum counter + 1 is calculated, and then it is set into id. After that, the value of id cannot change.

How to pass the correct value when calling a method?

I'm doing an assignment in which I have created an Appliance class that has a timePasses()method within it. This method re-directs some values that need to be stored within another method that is inside of another class. Here is where I am up to on this:
Appliance
public class ElectricCooker extends Cooker {
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState() {
if (varPass == 0) {
return isOff;
} else {
return isOn;
}
}
#Override
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses() {
if (varPass == isOff) {
varPass = 0;
} else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter
public class ElectricMeter {
ElectricMeter() {
}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
System.out.println(value);
}
public int incrementGenerated() {
}
public boolean canGenerate() {
}
public String getConsumed() {
}
public String getGenerated() {
}
}
Main method
public class MainCoursework {
public static void main(String[] args) {
ElectricMeter a = new ElectricMeter();
a.incrementConsumed(//what goes here?);
}
}
So the value from timePasses()has been redirected into an ElectricMeter instance but now I need to return that value to the increentConsumed() method in the meter class and I'm stuck on how to do this. Since the value of electricityConsumed is 20, the output should be 20. But instead I have to pass a parameter into a.incrementConsumed(//pass parameter here) and what ever is passed gets printed out onto the screen instead of the 20 from electrictyUse. Any help on how to do this is appreciated, thanks.
Actually, the incrementConsumed method is indeed implemented as you described:
public void incrementConsumed(int value)
{
System.out.println(value);
}
A method called incrementXXX shouldn't really output anything, should it? It should increment a variable/field:
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
You should declare another method that returns electricityUsed:
public int getElectricityUsed() {
return electricityUsed;
}
Now let's fix your main method.
In your main method, you didn't even create anything that consumes electricity! How can the electric meter incrementConsumed? So remove everything from the main method and create a cooker:
// your constructor looks weird. So I passed in some random arguments..
ElectricCooker cooker = new ElectricCooker(20, 0, 0, 60);
Now call timePasses to simulate that some time passed:
cooker.timePasses();
And print the electricity used:
System.out.println(ElectricMeter.getInstance().getElectricityUsed());
you need to create an instance variable in ElectricMeter and update that value on say incrementConsumed. When you want to print that use accessor of this variable.
public class Electric {
public static void main(String[] args) {
ElectricCooker cooker = new ElectricCooker(1,2,3,4);
//opertion on cooker
//ignoring best way for singleton creation
int electricityUse = ElectricMeter.getInstance().getElectricityUse();
System.out.println(electricityUse);
}
}
class ElectricCooker // extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
public int electricityUse = -1;
public int currentState() {
if (varPass == 0)
return isOff;
else {
return isOn;
}
}
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
public void timePasses() {
if (varPass == isOff)
varPass = 0;
else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
this.electricityUse = 5 * incrementTime;
}
}
class ElectricMeter {
public int electricityUse = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
this.electricityUse = value;
}
public int getElectricityUse() {
return electricityUse;
}
}
In ElectricMeter, some operations don't perform what they should.
ElectricMeter.getInstance().incrementConsumed(electricityUse);
should increment something but it writes only in the output:
public void incrementConsumed(int value){
System.out.println(value);
}
You should write it rather :
public void incrementConsumed(int value){
consumed+=value;
}
and add a private int consumed field in ElectricMeter class to store the actual consumed.
And your getConsumed() which has a empty implementation :
public String getConsumed(){
}
should simply return the consumed field and you should return a int value and not a String.
public int getConsumed() {
return consumed;
}
In this way, you can do :
public static void main(String[] args){
ElectricMeter.getInstance().incrementConsumed(20);
int consumed = ElectricMeter.getInstance().getConsumed();
}

Java error - invalid method declaration; return type required

I'm trying to complete this java program, but every time I try to compile it I get this error. Can someone figure out why my program is doing this. It seems that no matter what I do I still happen to get an error on my program. I tried everything I know to see if it would work. Please someone help me.
import java.util.Scanner;
public class Period
{
private static String phrase;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
// this is where the error is occuring at.
public Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
The 'Sorter' method is missing a return type. It should be:
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0, newPhrase.indexOf("."));
}
The method is not called anywhere, so i am not sure if this is what you intended it to do.
add the void return type:
public void Sorter(String newPhrase) // HERE
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
There are a lot of errors in the above code - see below for some code that runs, though i can't be sure it does exactly what you want given the limited scope of the question.
I don't want to stray too far from the original question, but you should really consider using instance variables and encapsulating your data, rather than relying on static variables.
import java.util.Scanner;
public class Period
{
private static String phrase;
private static int[] alphabet = new int [27];
public static void main(String [] args)
{
System.out.println("Enter a sentence with a period at the end.");
Scanner keyboard = new Scanner(System.in);
phrase = keyboard.nextLine().toLowerCase();
Period period = new Period();
period.entryPoint();
}
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}

An Arraylist of Arrays or os there a better way?

So thanks to the wonderful people here i've managed to get something semi workable, still have a couple bugs but maybe you guys can help me figure it out. So far none of the solution provided were a exact match (which is why i havent up voted them) but they did help me look at things in a new way and get things moving forward. So here is the current problem.
First the code then the explination
RaceButtons[RaceCounter] = new JToggleButton();
RaceButtons[RaceCounter].setIcon(RCiconSM);
RaceButtons[RaceCounter].setBorder(BorderFactory.createEmptyBorder());
RaceButtons[RaceCounter].setContentAreaFilled(false);
RaceButtons[RaceCounter].setActionCommand(temp_race.getRaceNameString(RaceCounter));
RaceButtons[RaceCounter].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Race race = new Race(1, 1, GenderList[PHYSICAL_SEX]);
race.setRaceID(race.getRaceIDFromString(ae.getActionCommand()));
//System.out.println(race.getraceID());
if (RaceButtons[race.getraceID()].isSelected()){
RaceButtons[race.getraceID()].setBorderPainted(true);
RaceButtons[race.getraceID()].setBorder(new LineBorder(Color.blue,2));
MyRaceArray.add(new Race(race.getraceID(), 1, GenderList[PHYSICAL_SEX]));
}else{
RaceButtons[race.getraceID()].setBorderPainted(false);
};
So first i create an array of Toggle buttons and when you click it it draw the border and then getting it's info i can add it to the array for races but this lives me with another problem i cant quite figure the logic off. Namly if there are already selected button it adds another instances to the button, it shouldn't do that it should ignore iexaisting entries but that means i have to check the arry for a matching object of type Race withthe same info right? What's the best way to do that?
And when you deselect it how do i remove that same object.
This is how your code should look like with a Race class:
import java.util.ArrayList;
import java.util.List;
public class Race {
private int raceID;
private double purity;
private int strMod;
private int dexMod;
private int conMod;
private int wisMod;
public int getRaceID() {
return raceID;
}
public void setRaceID(int raceID) {
this.raceID = raceID;
}
public double getPurity() {
return purity;
}
public void setPurity(double d) {
this.purity = d;
}
public int getStrMod() {
return strMod;
}
public void setStrMod(int strMod) {
this.strMod = strMod;
}
public int getDexMod() {
return dexMod;
}
public void setDexMod(int dexMod) {
this.dexMod = dexMod;
}
public int getConMod() {
return conMod;
}
public void setConMod(int conMod) {
this.conMod = conMod;
}
public int getWisMod() {
return wisMod;
}
public void setWisMod(int wisMod) {
this.wisMod = wisMod;
}
#Override
public String toString() {
return "Race [raceID=" + raceID + ", purity=" + purity + ", strMod="
+ strMod + ", dexMod=" + dexMod + ", conMod=" + conMod
+ ", wisMod=" + wisMod + "]";
}
public static void main(String args[]) {
//create a list of race objects
List<Race> raceCollection = new ArrayList<Race>();
//create a race object
Race race = new Race();
race.setRaceID(1);
race.setPurity(0.75);
race.setStrMod(5);
race.setDexMod(7);
race.setConMod(-2);
race.setWisMod(3);
//add race object to collection
raceCollection.add(race);
//You can create and add multiple objects of race to the collection
//Iterate your list and print the objects
for(Race raceObj:raceCollection) {
System.out.println(raceObj);
}
}
}
You will be able to make it work using an ArrayList of arrays, but that possibly isn't the best way in the long run. It can be very fiddly and error-prone to deal with - what happens when you insert a new race or attribute, but forget to to change the index somewhere?
Arrays and ArrayLists are usually best reserved for situations where you actually have a sequence / list (often with a meaningful sequence order).
In your case I'd be more inclined to adopt a prototype model. Typically in Java you would represent each race with a HashMap (or a data structure containing a HashMap), there the map represents the relationship between the "Attribute ID" and the "Default Value".
Creating a new elf is then just a case of initialising the elf's attributes using the default values from his race (or a average of different races, if you want...)
Some people may suggest making an OOP class with lots of named fields. This can also work, but IMHO a prototype model is better - it gives you much more flexibility in the long run. You often want to process large groups of attributes in the some way, and doing this is pretty messy if you have to refer to each of the attribute fields individually.
import java.util.ArrayList;
import java.util.List;
public class Race
{
private final int raceID;
private final double purity;
private final int strMod;
private final int dexMod;
private final int conMod;
private final int wisMod;
public Race (int raceID, double purity, int strMod, int dexMod, int conMod, int wisMod)
{
this.raceID = raceID;
this.purity = purity;
this.strMod = strMod;
this.dexMod = dexMod;
this.conMod = conMod;
this.wisMod = wisMod;
}
public int getRaceID ()
{
return raceID;
}
public double getPurity ()
{
return purity;
}
public int getStrMod ()
{
return strMod;
}
public int getDexMod ()
{
return dexMod;
}
public int getConMod ()
{
return conMod;
}
public int getWisMod ()
{
return wisMod;
}
#Override public String toString ()
{
return "RaceID:" + raceID
+ " purity:" + purity
+ " strMod:" + strMod
+ " dexMod:" + dexMod
+ " conMod:" + conMod
+ " wisMod:" + wisMod;
}
#override public int hashCode ()
{
return raceID;
}
#override public boolean equals (Race r)
{
return (r != null && this.raceID == r.getRaceID());
}
#override public Object clone ()
{
return new Race(this.raceID,this.purity,this.strMod,this.dexMod,this.conMod,this.wisMod);
}
public static void main(String args[])
{
// simple test
ArrayList<Race> races = new ArrayList<Race>();
Race a = new Race(0,0.5,1,2,3,4);
Race b = new Race(1,0.75,2,3,4,5);
Race c = new Race(2,0.25,-1,-2,-3,-4);
races.add(a);
races.add(b);
races.add(c);
for(Race race : races)
{
// System.out.println(race.toString());
System.out.println(race);
}
}
}
Then we have the visual model, which can be handled like this:
class RacePanel implements ActionListener
{
private Map<Integer,JToggleButton> r;
private Map<Integer,Race> f;
public RacePanel()
{
r = new TreeMap<Integer,JToggleButton>();
f = new TreeMap<Integer,Race>();
}
public JToggleButton add (Race a)
{
JToggleButton button = new JToggleButton();
button.setIcon(RCiconSM);
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
button.setActionCommand(a.getRaceID());
button.addActionListener(this);
r.put(a.getRaceID, button);
f.put(a.getRaceID, a);
}
public void remove (int raceID)
{
r.remove(a.getRaceID);
f.remove(a.getRaceID);
}
// When a button is clicked
public void actionPerformed(ActionEvent e)
{
// related race
Race a = f.get(e.getActionCommand());
// clicked button
JToggleButton b = r.get(e.getActionCommand());
// ..
}
public ArrayList<JToggleButton> getButtonList ()
{
return new ArrayList<Value>(r.values());
}
public ArrayList<Race> getRaceList ()
{
return new ArrayList<Value>(f.values());
}
public Race getRace (int raceID)
{
return f.get(raceID);
}
public JToggleButton getButton (int raceID)
{
return r.get(raceID);
}
// ..
}

Communication between 2 Classes

I'm a newbie java programer and I'm trying to make my first project.
I need to pass a variable between 2 classes, which is going fine. The problem is that the variable has a changing value and i cannot pass the actual value. Here is an example:
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
//here some code which will increase or decrease the value of the counter variable
//lets say for the sake of the example that at this point the value of the variable is 1.
//counter = 1;
}
public class B{
public static void main(String[] args) {
A a = new A();
System.out.println(a.getCounter());// here I need the actual counter variable value which is currently: 1
}
}
My problem is that i always receive 0. How can i pass the actual value of the variable.
Any help or advice is greatly appreciated.
A a = new A();
After instantiation (above statement) you need to call the method which will increment the counter here.
Example:
a.incrementCounter();
Then below statement will get counter value.
System.out.println(a.getCounter());
lets say for the sake of the example that at this point the value of the variable is 1.
No, by the time that code is read, the value did not change. All you do inside a class-block is to define a class, the “template” for an object. At that time, no values are set though.
The a.getCounter() you use already does the correct job: It returns the current value of a’s counter variable. If it does not return 1, then obviously the value hasn’t changed yet.
public class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public void increaseCounter() {
counter++;
}
}
public class B {
public static void main() {
A a = new A();
System.out.println(a.getCounter());
a.increaseCounter();
System.out.println(a.getCounter());
}
}
Make variable static so that it will be associated with class.
public class A{
private static int counter = 0;
public int getCounter(){
counter++;
return counter;
}
public static void main(String[] args) {
A a = new A();
a.setCounter(5);
System.out.println(a.getCounter());
}
public class A{
private int counter = 0;
public int getCounter(){
return counter;
}
public void setCounter(int count ){
this.counter=count;
}
}
Use constructors/setter...
public class A{
private int counter = 0;
public A(int c){
counter = c
}
public int getCounter(){
return counter;
}
public void setCounter(int c){
counter = c;
}
public void incCounter(){
counter++;
}
}
public class B{
public static void main(String[] args) {
A a = new A(123);
System.out.println(a.getCounter());
a.setCounter(456);
System.out.println(a.getCounter());
a.incCounter();
System.out.println(a.getCounter());
}
}
class A {
private int counter = 0;
public int getCounter() {
return counter;
}
public int increment() {//////////create increment Method which will increase the counter , or do any function you want
return counter++;
}
public void setCounter(int c) {///////////this method will allow you to set the counter
counter=c;
}
}
class B {
public static void main(String[] args) {
A a = new A();
a.increment();///////if you call this function will change your counter , if not , you will get it = 0
System.out.println(a.getCounter());
}
}
A a = new A();
System.out.println(a.getCounter());
The Output = 0
A a = new A();
a.increment();
System.out.println(a.getCounter());
The Output =1
a = new A();
a.setCounter(10);//////////here you set the `counter` by 10
System.out.println(a.getCounter());
The Output =10;
You have one class (Counter) which manages the counter int variable.
You would like for one or more other classes to be able to increment and/or get the counter value.
In that case, each instance of those classes should have a reference to the same instance of Counter (stored as member variable, passed to their constructor or a setter method).
class Counter {
private int counter = 0;
public int getValue() { return counter; }
public void increment() { counter++; }
public String toString() { return Integer.toString(counter); }
}
class CounterUser {
private final Counter counter;
public CounterUser(Counter counter) { this.counter = counter; }
public String toString() { return Integer.toString(counter.getValue()); }
}
class Test {
public static void main(String[] args) throws Exception {
Counter counter = new Counter();
CounterUser a = new CounterUser(counter);
CounterUser b = new CounterUser(counter);
System.out.printf("%s %s %s\n", counter, a, b);
counter.increment();
System.out.printf("%s %s %s\n", counter, a, b);
b.increment();
System.out.printf("%s %s %s\n", counter, a, b); }
}
Output:
0 0 0
1 1 1
2 2 2
You can do it from the constructor and/or create method that changes the value.
public class A
{
private int counter = 0;
public A()
{
// value is set first time you create an instance of A. (e.g when you do A a = new A();
counter = 1;
}
public int getCounter()
{
return counter;
}
public void incrementCounter()
{
counter++;
}
}
public class B
{
public static void main(String[] args)
{
A a = new A();
System.out.println(a.getCounter());// Output : 1
a.incrementCounter();
System.out.println(a.getCounter());// Output : 2
a.incrementCounter();
a.incrementCounter();
a.incrementCounter();
System.out.println(a.getCounter());// Output : 5
}
}

Categories

Resources