Java class, trying to make a method that finds the initial value - java

I'm just starting to learn classes, and I'm a bit stuck. I'm not sure how I can get this method to find the initial value that was first entered
public class DecreasingCounter {
private int value;
public DecreasingCounter(int valueAtStart) {
this.value = valueAtStart;
}
public void printValue() {
// do not touch this!
System.out.println("value: " + this.value);
}
public void decrease() {
if (this.value > 0) {
this.value--;
}
}
public void reset() {
this.value = 0;
}
public void setInitial() {
this.value =
}
}
it's the last method setInitial();that I'm trying to get to work.

You'll just need to maintain a reference to the initial value as a member so you can refer back to it later.
private final int initialValue;
And then modify your constructor like so
public DecreasingCounter(int valueAtStart) {
//store the initial value based on the arg passed in
this.initialValue = valueAtStart;
//go ahead and do whatever we do to reset our counter to the
//initial value (avoids duplicating code)
this.setInitial();
}
And then finally,
public void setInitial() {
//reset our current value back to the initial value we stored at construction time
this.value = this.initialValue;
}

Related

The use of a reference variable in this java code

Why is the reference variable ‚Input inside‘ necessary?
How does the ‚Input inside‘ work here?
What does the code: The code adds 5 to the x-value (in this case 4) and uses the square of the new value. So (4+5)^2.
Thank you. 😀
Code:
abstract class Input {
protected Input inside;
public Input() {
}
public Input(Input inside) {
this.inside = inside;
}
public int calculate(int value) {
if(inside == null) {
return value;
}
return inside.calculate(value);
}
public static void main(String[] args) {
Input chaincalculate = new Square(new AddFive());
int x;
x = 4;
System.out.println("The value is: " + (int) chaincalculate.calculate(x));
}
}
class AddFive extends Input {
public AddFive() {
}
public AddFive(Input inside) {
super(inside);
}
public int calculate(int value) {
value = super.calculate(value);
return value+5;
}
}
class Square extends Input {
public Square() {
}
public Square(Input inside) {
super(inside);
}
public int calculate(int value) {
value = super.calculate(value);
return value * value;
}
}
}
All the classes extending the abstract class Input, have their own calculate methods, and since, these classes, would want to use the abstract class Calculate method, the reference variable input inside is necessary to invoke/reference the calculate method residing in Input abstract class, to support the method chaining implemented in the code

Check if primitive has been set

Given a very simple class:
class MyClass {
int id;
double value;
MyClass(int id) {
this.id = id;
}
void setValue(double v) {
value = v;
}
boolean isValueUnassigned() {
return value == 0;
}
}
To check if value has not been assigned yet, is it OK if I just do return value == 0; since a double is 0 by default?
You should go for wrapper class for double which is Double. For Double data type default value would be null. So that there would not be any ambiguity. If value is null, then it's not assigned any value.
Well, yes primitive double is set to 0.0 by default. But if you simply do return value == 0; you can't be sure if someone called setValue(0) before, but it is a valid assignment too. If you want to be 100% sure if someone called the setValue() I would suggest something like this:
class MyClass {
private int id;
private double value;
private boolean valueSet; // is false by default
public MyClass(int id) {
this.id = id;
}
public void setValue(double v) {
value = v;
valueSet = true;
}
public boolean isValueSet() {
return valueSet;
}
}
Adding to what #Harshal has already said. Code for something like that would look like:
class MyClass {
private int id;
private Double value;
public MyClass(int id) {
this.id = id;
}
public void setValue(double v) {
value = v;
}
public double getValue() {
//Check for null pointer and return
if(value == null)
return <whatever you want>;
return value.doubleValue();;
}
public boolean isValueSet() {
return (value == null ? false : true);
}
}
You can use Double to reinitialize the double using following
class MyClass {
int id;
Double value;
MyClass(int id) {
this.id = id;
}
void setValue(Double v) {
value = v;
}
boolean isValueUnassigned() {
return value == null ? false : true;
}
}
Explanation
The main issue here is that, whatever double value you choose, e.g. 0 or -1, it could actually be a valid value set by the user. In which case your application would falsely return that it was not set yet, while it was.
What you need is called a sentinel value, i.e. a special value that indicates this case. Typically there are 3 approaches:
Flag
Introduce a simple boolean flag boolean isSet which you initialize to false and set to true once it was set.
This approach is good and really fast. But does not scale well if you, for example, start to introduce hundreds of such values for which you need to represent "not set yet".
double value;
boolean isValueSet = false;
void setValue(double value) {
this.value = value;
isValueSet = true;
}
boolean isValueUnassigned() {
return !isValueSet;
}
Object wrapper
Object variables can, additionally to their actual values/instances also refer to null. This can be used as sentinel to indicate the special case.
So you could go for having the value internally represented as Double instead of double, starting with null.
The disadvantage is that an object introduces quite some memory and performance overhead compared to a simple primitive. In this case it does not really matter but if you scale this up to a couple of thousands of them, you would definitely start to feel the impact.
Double value = null;
void setValue(double value) {
this.value = value; // auto-boxing
}
boolean isValueUnassigned() {
return value == null;
}
Sentinel value
If you application naturally allows that some values can never be used, you can use them as sentinel to indicate the case. A common example would be an age field for which you would not allow the user to set it to negative values. Then you can use, for example -1 to indicate it.
This approach is quite common and efficient. But it obviously is not always applicable and it is also not necessarily the most readable/maintainable approach.
double value = -1;
void setValue(double value) {
if (value < 0) {
throw new IllegalArgumentException("Negative values are not allowed");
}
this.value = value;
}
boolean isValueUnassigned() {
return value == -1;
}
The value is assigned when the object is created. You don't need a method to check if the value has been assigned because the answer is always yes.
Found the cleanest and clearest way to express it:
class MyClass {
int id;
Optional<Double> value;
MyClass(int id) {
this.id = id;
this.value = Optional.empty();
}
void setValue(double v) {
value = Optional.of(v);
}
double getValue() {
if (isValueUnassigned) {
throw new RuntimeException("Value has not been assigned");
}
return value.get();
}
boolean isValueUnassigned() {
return value.isEmpty();
}
}
a double value is 0 by default , but you can pass -1 to it .
double value = -1;
for check :
if (value!= -1) {
// To Do
}

Why is my function not returning the right value

I have a function that sets the value if and only the value given is contained in with the enum declared. I'm then trying to get the value via get Method but I'm getting the default value. The setter method is not getting the new value and updating it.
public enum BranchLocations {ONE,TWO,THREE,FOUR,FIVE};
private String BranchName ="Branch Name";
public boolean setBranchLocation(String branchLocation) {
for (BranchLocations b : BranchLocations.values()) {
if (b.name().equals(branchLocation)) {
this.BranchName = branchLocation;
return true;
}
}
return false;
}
public String getBranchLocation() {
return this.BranchName ;
}
I'm learning enum currently and not very familiar with it. I'm just checking if the value is contained in the enum by a for loop and .equals method
clarification - tester im running it against
public class Main {
public static void main(String[] args){
Bank bank = new Bank("LhblVEWZXmtjn3gMykBaqfN& &h", Bank.BranchLocations.values()[0]);
System.out.println(Bank.BranchLocations.values()[0]);
System.out.println(Bank.BranchLocations.values()[1].toString());
String newBranchLocation = Bank.BranchLocations.values()[1].toString();
System.out.println(bank.getBranchLocation());
bank.setBranchLocation(newBranchLocation);
System.out.println(bank.getBranchLocation());
System.out.println(
(bank.setBranchLocation(newBranchLocation) && bank.getBranchLocation().equals(newBranchLocation)));
}
}
public enum BranchLocations {
ONE("ONE"),
TWO("TWO"),
THREE("THREE"),
FOUR("FOUR"),
FIVE("FIVE");
private String BranchName = new String();
BranchLocations(String val){BranchName = val;}
public String getBranchLocation() {return BranchName;}
public boolean setBranchLocation(String branchLocation) {
for (BranchLocations b : BranchLocations.values()) {
if (b.name().equals(branchLocation)) {
this.BranchName = branchLocation;
return true;
}
}
return false;
}
}
In the enum, you have just declared the names, not the values. But, in your method, you are retrieving the values for the test. This is not the intended behaviour.
Do:
if (b.toString().equals(branchLocation)) {
this.BranchName = branchLocation;
return true;
}
or define a value for each one of the names in the Enum:
public enum BranchLocations {
ONE("ONE"),
TWO("TWO"),
THREE("THREE"),
FOUR("FOUR"),
FIVE("FIVE")
};

Logic error possibly misunderstanding in java assignment

I've been having numerous problems getting this project to work correctly but I'm currently stuck on getting this class to work properly. Whats its suppose to do is take the current station from the radio class and pass it along to this class. The problem is i'm trying to select between AM and FM but every time i run it, it only displays the AM station. I don't understand why it automatically gets set to that station.
public class AutoRadioSystem
{
private Radio selectedRadio;
private AMRadio radioAM;
private FMRadio radioFM;
private XMRadio radioXM;
//is this the correct place to initialize these?
Radio amRadio = new AMRadio();
Radio fmRadio = new FMRadio();
public AutoRadioSystem()
{
//even making the selected radio FM still produces values for AM
selectedRadio = radioFM;
}
// this is where my problem currently lies and probably much more. Shouldn't it return 0.0 without any station being selected.
public double getCurrentStation()
{
if (selectedRadio == radioAM)
{
return amRadio.getCurrentStaion();
}
else if (selectedRadio == radioFM)
{
return fmRadio.getCurrentStaion();
}
return 0.0;
}
//I'm not sure if i'm setting this up correctly to switch the radio from am to fm
public void selectRadio()
{
if (selectedRadio == radioAM)
selectedRadio = radioFM;
}
public static void main (String [] args) {
AutoRadioSystem c = new AutoRadioSystem();
c.selectRadio();
double b = c.getCurrentStation();
System.out.println(b);
}
}
public class AMRadio extends Radio
{
private static final double Max_Station = 1605;
private static final double Min_Station = 535;
private static final double Increment = 10;
public AMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("AM " + this.currentStation);
return message;
}
}
public class FMRadio extends Radio
{
private static final double Max_Station = 108.0;
private static final double Min_Station = 88.0;
private static final double Increment = .01;
public FMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("FM " + this.currentStation);
return message;
}
}
public abstract class Radio
{
double currentStation;
RadioSelectionBar radioSelectionBar;
public Radio()
{
}
public abstract double getMax_Station();
public abstract double getMin_Station();
public abstract double getIncrement();
public void up()
{
}
public void down()
{
}
public double getCurrentStaion()
{
return this.currentStation;
}
public void setCurrentStation(double freq)
{
this.currentStation = freq;
}
public void setStation(int buttonNumber, double station)
{
}
public double getStation(int buttonNumber)
{
return 0.0;
}
public String toString()
{
String message = ("" + currentStation);
return message;
}
}
The problem is, in .getCurrentStation(), both selectedRadio & radioAM is not init and is null.
The mistake begin with:
public void selectRadio()
{
if (selectedRadio == radioAM)
{
selectedRadio = radioFM;
}
}
Here, the selectedRadio = null, so it's never get assign value.
Edit: I believe you're just begin with this, so a little more details will help.
You make mistake when declare two field, amRadio & radioAM then init one of them and use another.
You didn't set value to selectedRadio and compare it, this always return false
The best place to init value for an instance is the constructor method, here is AutoRadioSystem()
You may want to change the code to like this:
private Radio selectedRadio;
public AutoRadioSystem()
{
selectedRadio = new FMRadio();
}
// To compare, using instanceOf, but better design will use enum value instead, up to you
I think I've found the problem
You have 2 fields for each Radio overload
private AMRadio radioAM;
...
Radio amRadio = new AMRadio();
but the one you're comparing to: radioAM never gets instantiated, and therefore is always null.
When you call
if (selectedRadio == radioAM)
both selectedRadio and radioAM are null, so of course they would be equal
unless you intend radioAM and amRadio to be completely different instances, than you shouldn't have 2 fields like that.
Since you're using polymorphism, you might want to use the latter one
Radio amRadio = new AMRadio();
All properties selectedRadio, radioAM and RadioFM are null. The code in the constructor has no effect because selectedRadio = RadioFM. This means that selectedRadio its value does not change and remains zero.
Therefore selectedRadio == radioAM (null == null) in getCurrentStation is always true.This will always apply the first if-block in your method getCurrentStation and will always return the "amradio".
Caio

Setting a value in a class is not working

I have a class called monetary
public class Monetary
{
double value;
String type;
public Monetary()
{
value = 0;
type = "";
}
public double getValue()
{
return value;
}
public void setValue(double x)
{
x = this.value;
}
and i was testing get and set methods so i made a testing class as the following
public class test
{
public static void main(String [] args)
{
double test = 5000;
Monetary testM = new Monetary();
testM.setValue(5000);
System.out.println(testM.getValue());
}
}
The problem is that the result java prints is not 5000.0, but 0. I don't get why this is happening. Aren't these methods correct?
The problem is in the setValue method:
public void setValue(double x) {
x = this.value;
}
You're assigning the parameter the current value of the attribute, it should be backwards:
public void setValue(double x) {
this.value = x;
}
Note that even doing this, you will get an output like 5000.0000000.... In order to fix the result you can use String#format or System.out.printf:
System.out.println(String.format("%.2f", testM.getValue()));
or
System.out.printf("%.2f\n", testM.getValue());
In your code you are assigning the value to parameter x, it should be opposite.
public void setValue(double x){
this.value = x;
}
try this:
public void setValue(double x)
{
this.value = x;
}
public void setValue(double x){
this.value = x;
}
You are assigning the parameter you've passed x with the default value of the value. You must be doing the exact opposite of that. Assign the value with the value passed x.
Hence, instead of this this.value = 5000, this is happening x = 0.
You are assigning the parameter (double x) the value of int value which does nothing because you are return value, so what you want to do is
public class Monetary
{
double value;
String type;
public Monetary()
{
value = 0;
type = "";
}
public double getValue()
{
return value;
}
public void setValue(double x)
{
value = x;//change this
}

Categories

Resources