I wrote my own AtomicDouble class and I also have a BankAccount class that does two simple withdrawals and deposits operations and it has an AtomicDouble instance(balance). The problem with my code is that when I call the addAndGet method in deposit(), the program falls into an infinite loop, and compareAndSet() never returns the true value, but when I debugged this, currentValue and the value from atomic.get () were equal, but this method does not understand.
The interesting thing is that when I put if (atomic.get()==currentValue) instead of if (atomic.compareAndSet(currentValue, nextValue)), the program runs properly.
public class AtomicDouble extends Number {
private final AtomicReference<Double> atomic;
public AtomicDouble() {
this(0.0);
}
public AtomicDouble(double initialValue) {
atomic = new AtomicReference<>(initialValue);
}
public final double addAndGet(double delta) {
while (true) {
double currentValue = atomic.get();
double nextValue = currentValue + delta;
if (atomic.compareAndSet(currentValue, nextValue))
return nextValue;
}
}
public final double incrementAndGet() {
return addAndGet(1);
}
public final void set(double newValue) {
atomic.set(newValue);
}
public final double get() {
return atomic.get();
}
public final double getAndSet(double newValue) {
return atomic.getAndSet(newValue);
}
public float floatValue() {
return (float) get();
}
#Override
public double doubleValue() {
return get();
}
public int intValue() {
return (int) get();
}
public long longValue() {
return (long) get();
}
public String toString() {
return Double.toString(get());
}
}
public class BankAccount {
private final AtomicDouble balance;
private String accountNumber;
public BankAccount(double balance, String accountNumber) {
this.balance = new AtomicDouble(balance);
this.accountNumber = accountNumber;
}
public void deposit(double number, String color) {
System.out.println(color + "deposit " + number + " current balance=" + balance.addAndGet(number));
}
public void withdraw(double number, String color) {
if (this.balance.get() - number >= 0) {
System.out.println(color + "Withdraw " + number + " current balance=" + balance.addAndGet(-number));
return;
}
System.out.println(color + "Not enough balance");
}
public static void main(String[] args) {
BankAccount bankAccount = new BankAccount(1000.0, "4234236");
ExecutorService threadsPool = Executors.newFixedThreadPool(2);
threadsPool.execute(new Runnable() {
#Override
public void run() {
bankAccount.deposit(300.0, ThreadColor.ANSI_YELLOW);
bankAccount.withdraw(50.0, ThreadColor.ANSI_YELLOW);
}
});
threadsPool.execute(new Runnable() {
#Override
public void run() {
bankAccount.deposit(203.75, ThreadColor.ANSI_BLUE);
bankAccount.withdraw(100.0, ThreadColor.ANSI_BLUE);
}
});
threadsPool.shutdown();
}
}
output: There is no output
I would suppose it is because of autoboxing. You can't have a reference to double, you have a reference to Double.
The operands get "reboxed" each time around the loop and therefore references are never identical. That is, the reference in currentValue is never the same as the reference in atomic.
Try using currentValue reference types.
public final double addAndGet(double delta) {
while (true) {
Double currentValue = atomic.get();
Double nextValue = currentValue + delta;
if (atomic.compareAndSet(currentValue, nextValue))
return nextValue;
}
}
(Fortunately, Double is an immutable type, otherwise this would have a race hazard)
Related
So I am currently learning about interfaces within java and in this program I created 3 separate classes Building.class, Bicycle.class, and Car.class and they are unrelated but they all use the CarbonFootPrint Interface. in my processCarbonFootPrintData class I created an arrayList that holds the data from my objects then I loop through the array list and I get this weird output that does not show the result of my input data.
package CarbonFootPrintPackage;
import java.util.Scanner;
/**
*
* #author cjt1496
*/
public class Building implements CarbonFootPrintInterface {
private int numberOfFloors;
private int numberOfJanitors;
private boolean isBuildingOpenOrClosed;
double naturalGasConsumed;
Scanner input = new Scanner(System.in);
public double getNaturalGasConsumed() {
return naturalGasConsumed;
}
public void setNaturalGasConsumed(double naturalGasConsumed) {
this.naturalGasConsumed = naturalGasConsumed;
}
public int getNumberOfFloors() {
return numberOfFloors;
}
public void setNumberOfFloors(int numberOfFloors) {
this.numberOfFloors = numberOfFloors;
}
public int getNumberOfJanitors() {
return numberOfJanitors;
}
public void setNumberOfJanitors(int numberOfJanitors) {
this.numberOfJanitors = numberOfJanitors;
}
public boolean isIsBuildingOpenOrClosed() {
return isBuildingOpenOrClosed;
}
public void setIsBuildingOpenOrClosed(boolean isBuildingOpenOrClosed) {
this.isBuildingOpenOrClosed = isBuildingOpenOrClosed;
}
public Building(){
}
public Building(int numberOfFloors, int numberOfJanitors, boolean isBuildingOpenOrClosed, double naturalGasConsumed) {
this.numberOfFloors = numberOfFloors;
this.numberOfJanitors = numberOfJanitors;
this.isBuildingOpenOrClosed = isBuildingOpenOrClosed;
this.naturalGasConsumed = naturalGasConsumed;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for a Building ");
System.out.println("--------------------------------------------------------");
System.out.println("How many therms of natural gas has your building consumed?");
naturalGasConsumed = input.nextDouble();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this building is " +
(getNaturalGasConsumed() * 11.7) + "pounds of CO2 from natural gas use.\n");
}
}
START OF CAR.CLASS
public class Car implements CarbonFootPrintInterface {
private int numberOfSeats;
private int steeringWheel;
double emissionConversionFactor;
double distanceTraveled;
int numberOfTimesTraveled;
Scanner input = new Scanner(System.in);
public int getNumberOfSeats() {
return numberOfSeats;
}
public void setNumberOfSeats(int numberOfSeats) {
this.numberOfSeats = numberOfSeats;
}
public int getSteeringWheel() {
return steeringWheel;
}
public void setSteeringWheel(int steeringWheel) {
this.steeringWheel = steeringWheel;
}
public double getEmissionConversionFactor() {
return emissionConversionFactor;
}
public void setEmissionConversionFactor(double emissionConversionFactor) {
this.emissionConversionFactor = emissionConversionFactor;
}
public double getDistanceTraveled() {
return distanceTraveled;
}
public void setDistanceTraveled(double distanceTraveled) {
this.distanceTraveled = distanceTraveled;
}
public int getNumberOfTimesTraveled() {
return numberOfTimesTraveled;
}
public void setNumberOfTimesTraveled(int numberOfTimesTraveled) {
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public Car(){
}
public Car(int numberOfSeats, int steeringWheel, double emissionConversionFactor, double distanceTraveled, int numberOfTimesTraveled) {
this.numberOfSeats = numberOfSeats;
this.steeringWheel = steeringWheel;
this.emissionConversionFactor = emissionConversionFactor;
this.distanceTraveled = distanceTraveled;
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for a Car ");
System.out.println("--------------------------------------------------------");
System.out.println("Enter your emissionConversionFactor (Must be a decimal)");
emissionConversionFactor = input.nextDouble();
System.out.println("Enter your distance traveled in km (Must be a decimal)");
distanceTraveled = input.nextDouble();
System.out.println("Enter the number of times you traveled to your destination");
numberOfTimesTraveled = input.nextInt();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this bicycle is " +
getEmissionConversionFactor() * (getDistanceTraveled() * getNumberOfTimesTraveled()) +"Kg CO2e\n");
}
}
START OF BICYCLE.CLASS
import java.util.Scanner;
public class Bicycle implements CarbonFootPrintInterface {
private int handleBars;
private boolean KickStand;
double emissionConversionFactor;
double distanceTraveled;
int numberOfTimesTraveled;
Scanner input = new Scanner(System.in);
public int getHandleBars() {
return handleBars;
}
public void setHandleBars(int handleBars) {
this.handleBars = handleBars;
}
public boolean isKickStand() {
return KickStand;
}
public void setKickStand(boolean KickStand) {
this.KickStand = KickStand;
}
public double getEmissionConversionFactor() {
return emissionConversionFactor;
}
public void setEmissionConversionFactor(double emissionConversionFactor) {
this.emissionConversionFactor = emissionConversionFactor;
}
public double getDistanceTraveled() {
return distanceTraveled;
}
public void setDistanceTraveled(double distanceTraveled) {
this.distanceTraveled = distanceTraveled;
}
public int getNumberOfTimesTraveled() {
return numberOfTimesTraveled;
}
public void setNumberOfTimesTraveled(int numberOfTimesTraveled) {
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public Bicycle(){
}
public Bicycle(int handleBars, boolean KickStand, double emissionConversionFactor, double distanceTraveled, int numberOfTimesTraveled) {
this.handleBars = handleBars;
this.KickStand = KickStand;
this.emissionConversionFactor = emissionConversionFactor;
this.distanceTraveled = distanceTraveled;
this.numberOfTimesTraveled = numberOfTimesTraveled;
}
public void calculateCarbonFootPrint(){
System.out.println("Now Calculating Carbon foot print for Bicycle ");
System.out.println("--------------------------------------------------------");
System.out.println("Enter your emissionConversionFactor (Must be a decimal)");
emissionConversionFactor = input.nextDouble();
System.out.println("Enter your distance traveled in km (Must be a decimal)");
distanceTraveled = input.nextDouble();
System.out.println("Enter the number of times you traveled to your destination");
numberOfTimesTraveled = input.nextInt();
}
#Override
public void getCarbonFootPrint() {
System.out.println("The carbon foot print emitted from this bicycle is " +
getEmissionConversionFactor() * (getDistanceTraveled() * getNumberOfTimesTraveled()) +"Kg CO2e\n");
}
START Of PROCESS_CARBON_FOOTPRINT_DATA CLASS
public class ProcessCarbonFootPrintData {
public void createCarbonFootPrint(){
Building newBuilding = new Building();
Car newCar = new Car();
Bicycle newBicycle = new Bicycle();
newBuilding.calculateCarbonFootPrint();
newCar.calculateCarbonFootPrint();
newBicycle.calculateCarbonFootPrint();
ArrayList footPrint = new ArrayList();
footPrint.add(newBuilding);
footPrint.add(newCar);
footPrint.add(newBicycle);
for (Object footPrint1 : footPrint) {
System.out.println(footPrint1.toString());
}
}
}
This is the output I am getting:
CarbonFootPrintPackage.Building#42a57993
CarbonFootPrintPackage.Car#75b84c92
CarbonFootPrintPackage.Bicycle#6bc7c054
ArrayList footPrint = new ArrayList();
footPrint.add(newBuilding);
footPrint.add(newCar);
footPrint.add(newBicycle);
for (Object footPrint1 : footPrint) {
System.out.println(footPrint1.toString());
}
Your arraylist contains Objects, it doesn't know anything further of the type. When you do:
for ( Object footPrint1 : footPrint) {
}
You also declare the elements to be of type Object.
There are two things you need to do:
Be specific about the type. If you want to keep your List as is, with the different types, change your loop to:
for ( Object footPrint1 : footPrint) {
if ( footPrint1 instanceof Car )
System.out.println((Car)footPrint1);
else if ( footPrint1 instanceof Building )
System.out.println((Building)footPrint1);
else System.out.println((Bicycle)footPrint1);
}
This way, it'll know what type of data to print.
By just doing that, you'll still run into the same issue, because you haven't overridden your toString methods.
Add the following to your Car class:
#Override
public String toString() {
return "I am a car!!";
}
and you'll see that for the Car instance, that line is printed, instead of the memory address.
Override that method for all your classes, and alter the value returned by it the way you want it to be.
So I've been trying to figure out how Collections work in Java (by looking at an old project we did in uni) but I keep getting some errors I cannot fix, it has something to do with the Comparable function
This is my first class:
import java.io.*;
import java.util.*;
public class Client {
private int hour;
private int minute;
private int min_per_stay;
private double price;
public Client(int h, int m, int mps, double p)
{
this.hour = h;
this.minute = m;
this.min_per_stay = mps;
this.price = p;
}
public void SetHour(int h)
{
this.hour = h;
}
public void SetMin(int m)
{
this.minute = m;
}
public void SetMinPStay(int mps)
{
this.min_per_stay = mps;
}
public void SetPrice(double p)
{
this.price = p;
}
public int GetHour()
{
return hour;
}
public int GetMin()
{
return minute;
}
public int GetMinPStay()
{
return min_per_stay;
}
public double GetPrice()
{
return price;
}
public String toString()
{
return "Hours: " + this.hour +
" Minutes: " + this.minute +
" Minutes per stay:" + this.min_per_stay +
" Price: " + this.price + "\n";
}
public boolean equals(Client c) {
return (this.hour == ((Client)c).GetHour() && this.minute == ((Client)c).GetMin());
}
public int CompareTo(Client c)
{
if (this.hour<((Client)c).hour) return -1;
if(this.minute<((Client)c).minute) return -1;
if (this.hour>((Client)c).hour) return 1;
if(this.minute>((Client)c).minute) return 1;
return 0;
}
}
And my collection:
import java.io.*;
import java.util.*;
public class ClientCollection{
private SortedSet<Client> oClient = new TreeSet<Client>();
public ClientCollection()
{
}
public ClientCollection(String FileName)
{
try
{
Scanner sc = new Scanner(new File(FileName));
while(sc.hasNextLine())
{
oClient.add(new Client(sc.nextInt(),sc.nextInt(),
sc.nextInt(),sc.nextDouble()));
}
sc.close();
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
public void addClient(Client c)
{
oClient.add(c);
}
public List<Client> reverseList()
{
List<Client> oList1 = new ArrayList<Client>(oClient);
List<Client> oList2 = new ArrayList<Client>();
for(ListIterator<Client> it = (oList1.listIterator(oClient.size())); it.hasPrevious(); )
{
Client res = it.previous();
oList2.add(res);
}
return oList2;
}
public void printColl()
{
System.out.println(oClient.toString());
}
public static void main(String[] args)
{
ClientCollection oc = new ClientCollection("test.txt");
oc.printColl();
oc.reverseList();
oc.printColl();
}
}
and the errors I get are:
Exception in thread "main" java.lang.ClassCastException: Client cannot be cast to java.base/java.lang.Comparable
at java.base/java.util.TreeMap.compare(Unknown Source)
at java.base/java.util.TreeMap.put(Unknown Source)
at java.base/java.util.TreeSet.add(Unknown Source)
at ClientCollection.<init>(ClientCollection.java:20)
at ClientCollection.main(ClientCollection.java:56)
i'll be really happy if someone explains the errors to me, im still kinda new at this :(
Your Client class doesn't implement the Comparable<Client> interface (i.e. Client doesn't have a natural ordering).
Therefore, in order for it to be used as an element of a TreeSet, you must pass to the TreeSet<Client> constructor a Comparator<Client>, which specifies the ordering of Client elements.
Failing to do so results in ClassCastException, since the TreeSet class (or rather the TreeMap class that is uses behind the scenes) assumes that if you didn't supply a Comparator in the constructor, this means that your Client implements Comparable.
EDIT: Since you have a CompareTo method in the Client class, it looks like you intended to implement Comparable.
Change:
public class Client
to:
public class Client implements Comparable<Client>
and change:
public int CompareTo(Client c)
to:
public int compareTo(Client c)
You might want to modify the logic of your compareTo method, though.
Apart from what #Eran wrote, you need to write method names starting with a lower case letter. You can see that StackOverflow's formatter gets confused by it. It will also confuse anybody having to maintain your code.
Your compareTo method should look like this:
public int compareTo(final Client c)
{
final int diffHours = this.hour - c.hour;
if (diffHours == 0) {
return this.minute - c.minute;
} else {
return diffHours;
}
}
The casts are unnecessary, since the c parameter is already of type Client.
I was looking for some good patterns to have possibility to express distance in different units. I found Martin Fowler article about quantities and I programmed something like:
Here is Distance class ( I think it is not necessery to make it abstract ):
public class Distance {
double mValue;
DistanceUnit mUnit;
public Distance(double value, DistanceUnit unit){
this.mValue = value;
this.mUnit = unit;
}
public Distance toUnit(DistanceUnit unit){
double factor = this.mUnit.getMetresFactor()/unit.getMetresFactor();
double newValue = this.mValue * factor;
Distance distance = new Distance(newValue, unit);
return distance;
}
#Override
public String toString(){
return String.valueOf(mValue);
}
}
It looks very simple. Conversion toUnit is based on DistanceUnit method getMetresFactor. Each Unit class implements DistanceUnit interface and has method getMetresFactor() like:
public interface DistanceUnit {
double getMetresFactor();
}
public class Inch implements DistanceUnit {
#Override
public double getMetresFactor() {
return 0.0254;
}
}
public class Kilometer implements DistanceUnit {
#Override
public double getMetresFactor() {
return 1000.0;
}
}
And the usage is for example:
Distance inches = new Distance(300.0, new Inch());
Distance kilometres = inches.toUnit(new Kilometres());
So it returns the correct value.
Is it good way to store distance in this way? Maybe you know some weaknesses of this approach. Maybe is a good idea to use here a FactoryMethod pattern to construct distance based on unit shortcut like "m" for meter. I think about the amount of classes if I would have a lot of units... Is it good idea to have factory which return factor of meters based on unit name? There will be no classes for units then?
Hm, i would use enum instead of DistanceUnit classes, because there is no different instances of them.
You can set a value to enum like here
and then call enum.getValue() instead of unit.getMetresFactor().
Also it is a little bit confusing, is the mValue value in meters or in DistanceUnit's, if in meters, you must have
double factor = unit.getMetresFactor();
there
Ok and now with any convertion function support:
import java.util.HashMap;
import java.util.Map;
public abstract class MeasureConverter {
public abstract double valueToBasic(double value);
public abstract double basictoValue(double basic);
/**
*
*/
public static Map<String, MeasureConverter> converters;
public static Map<String, MeasureConverter> getConverters() {
if (converters == null) {
converters = new HashMap<String, MeasureConverter>();
converters.put("kilo", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value * 1000;
}
#Override
public double basictoValue(double basic) {
return basic / 0.001;
}
});
// taking the basic temperature value in kelvines
converters.put("kelvine", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value;
}
#Override
public double basictoValue(double basic) {
return basic;
}
});
converters.put("celsius", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value + 273.15;
}
#Override
public double basictoValue(double basic) {
return basic - 273.15;
}
});
converters.put("faren", new MeasureConverter() {
#Override
public double valueToBasic(double value) {
return value * 1.8 - 459.67 ; // or whatever is there?
}
#Override
public double basictoValue(double basic) {
return (basic + 459.67 ) / 1.8;// or whatever is there?
}
});
}
return converters;
}
}
And then :
import java.util.Objects;
public class MeasurePattern {
double value;
String name;
public MeasurePattern(double value, String name) {
this.value = value;
this.name = name;
}
#Override
public String toString() {
return "MeasurePattern{" + "value=" + value + ", name=" + name + '}';
}
#Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + (int) (Double.doubleToLongBits(this.value) ^ (Double.doubleToLongBits(this.value) >>> 32));
hash = 29 * hash + Objects.hashCode(this.name);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MeasurePattern other = (MeasurePattern) obj;
if (Double.doubleToLongBits(this.value) != Double.doubleToLongBits(other.value)) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
public MeasurePattern convertTo(String converter) {
MeasureConverter mycon = MeasureConverter.getConverters().get(name);
MeasureConverter hiscon = MeasureConverter.getConverters().get(converter);
double basic = mycon.valueToBasic(value);
double hisValue = hiscon.basictoValue(basic);
return new MeasurePattern(hisValue, converter);
}
public static void main(String[] args) {
//trying temperatures;
MeasurePattern temp = new MeasurePattern(10, "celsius");
MeasurePattern kelvine = temp.convertTo("kelvine");
MeasurePattern faren = kelvine.convertTo("faren");
MeasurePattern cels = faren.convertTo("celsius");
System.out.println("kelvine = " + kelvine);
System.out.println("faren = " + faren);
System.out.println("cels = " + cels);
}
}
Output:
kelvine = MeasurePattern{value=283.15, name=kelvine}
faren = MeasurePattern{value=412.67777777777775, name=faren}
cels = MeasurePattern{value=9.999999999999943, name=celsius}
You can implement it analog to java.util.concurrent.TimeUnit as an enum. E.g.
public enum DistanceUnit {
KILOMETER {
#Override
protected double conversionFactor(DistanceUnit toDistanceUnit) {
switch (toDistanceUnit) {
case KILOMETER:
return 1;
case MILE:
return 0.621371;
default:
throw new UnsupportedOperationException(toDistanceUnit + " is not supported");
}
}
},
MILE {
#Override
protected double conversionFactor(DistanceUnit toDistanceUnit) {
switch (toDistanceUnit) {
case KILOMETER:
return 1.60934;
case MILE:
return 1;
default:
throw new UnsupportedOperationException(toDistanceUnit + " is not supported");
}
}
};
public double toDistance(double value, DistanceUnit targetDistance) {
return value * conversionFactor(targetDistance);
}
protected abstract double conversionFactor(DistanceUnit toDistanceUnit);
}
change your Distance class to
public class Distance {
double mValue;
DistanceUnit mUnit;
public Distance(double value, DistanceUnit unit){
this.mValue = value;
this.mUnit = unit;
}
public Distance toUnit(DistanceUnit unit){
double newValue = mUnit.toDistance(mValue, unit);
Distance distance = new Distance(newValue, unit);
return distance;
}
#Override
public String toString(){
return String.valueOf(mValue);
}
}
and the client code will look very clear
public class Main {
public static void main(String[] args) {
Distance kilometers = new Distance(265.35, DistanceUnit.KILOMETER);
Distance miles = kilometers.toUnit(DistanceUnit.MILE);
System.out.println(miles);
}
}
will output
164.88079485000003
Java convention does not use a m(ember) prefix (but say a this. qualification), and convention is taken quite seriously in java (as opposed to C++ for instance).
toString misses the unit.
JScience offers more, the capability to calculate in different units, m/s², and so on. Your class is a nice abstraction. But in a wider context, you probably will want to have math operations, powers of units (-2 for s above).
Take a look at your own usage ideas first:
(Just garbage:)
U speedUnit = U.of(Distance::km, Time::h.up(-1));
double timeInS = U.mile(40).div(speedunit(30)).in(U.m);
I think you should use the "Strategy" pattern.
An interface:
public interface DistanceUnit {
double getDistance(int metres);
}
The Inch class:
public class Inch implements DistanceUnit {
#Override
public double getDistance(int metres) {
return meters*39; //do conversion here
}
}
The Kilometers class:
public class Kilometres implements DistanceUnit {
#Override
public double getDistance(int metres) {
return meters/1000; //do conversion here
}
}
Then:
List<DistanceUnit> distanceList = new ArrayList<>();
distanceList.add(new Inch());
distanceList.add(new Kilometres());
for (DistanceUnit item : distanceList) {
System.out.println(item.getDistance(1000));
}
If I understand you, I think it is a simple and clean solution.
You can follow this model for conversion between others units.
Help, I need some revision on this code. How do I get the values of 65 and 106 without removing it from Exercise3 myExer3 = new Exercise3(65,106);
Base Class:
public class Exercise3 {
private int Voltage;
private int Resistance;
public void setVoltage(int temp){
if (Voltage == 65)
Voltage = temp;
}
public void setResistance(int temp){
if (Resistance == 106 )
Resistance =106;
}
public int getVoltage (){
return (Voltage);
}
public int getResistance(){
return(Resistance);
}
}
Test Class:
public class Test_Excercise3 {
public static void main(String []args){
Exercise3 myExer3 = new Exercise3(65,106);
System.out.println("Voltage: "+myExer3.getVoltage());
System.out.println("Resistance: "+myExer3.getResistance());
System.out.println("Current : "+ (myExer3.getVoltage()/myExer3.getResistance()));
}
}
So that I could get the result of 0.61 Ohm's or the Current.
Your class needs a constructor:
public class Exercise3 {
private int voltage;
private int resistance;
public Exercise3(int voltage, int resistance) {
this.voltage = voltage;
this.resistance = resistance;
}
...
}
For more information, consult the Java Tutorials on providing constructors for your classes.
Add a constructor to the Excercise3 and correct setters, also do conversion to (double) of the result.
public class JavaApplication27
{
public static class Exercise3
{
private int voltage;
private int resistance;
public void setVoltage(int v)
{
voltage = v;
}
public void setResistance(int res)
{
resistance = res;
}
public int getVoltage()
{
return voltage;
}
public int getResistance()
{
return resistance;
}
public Exercise3(int v, int res)
{
setVoltage(v);
setResistance(res);
}
public double getCurrent() //helper method :)
{
return (double) getVoltage() / getResistance();
}
}
public static void main(String[] args)
{
Exercise3 myExer3 = new Exercise3(65, 106);
System.out.println("Voltage : " + myExer3.getVoltage());
System.out.println("Resistance: " + myExer3.getResistance());
System.out.println("Current : " + ( (double) myExer3.getVoltage() / myExer3.getResistance())); // Since resistance and voltage are int's, the result of int/int division is int. To get a double) result use (double) :).
System.out.println("Current : " + myExer3.getCurrent()); //you may also use helper method to calculate current
System.out.format( "Current : %.2f", myExer3.getCurrent() ); // to get .61 must use formatter
}
}
Output:
Voltage : 65
Resistance: 106
Current : 0.6132075471698113
Current : 0.6132075471698113
Current : 0.61
abstract class CustomException extends Exception
{
abstract public String toString();
abstract public String getMessage();
}
interface SimpleInterestCalculator
{
public void setPrincipalAmount(int principalAmount) throws CustomException;
public int getPrincipalAmount();
public void setRateOfInterest(int rateOfInterest) throws CustomException;
public int getRateOfInterest();
public void setTime(int Time) throws CustomException;
public int getTime();
public int getSimpleInterest();
}
interface CompoundInterestCalculator
{
public void setPrincipalAmount(int principalAmount) throws CustomException;
public int getPrincipalAmount();
public void setRateOfInterest(int rateOfInterest) throws CustomException;
public int getRateOfInterest();
public void setTime(int Time) throws CustomException;
public int getTime();
public int getCompoundInterest();
}
class SimpleInterestCalculationException extends CustomException
{
String message;
SimpleInterestCalculationException(String message)
{
this.message = message;
}
SimpleInterestCalculationException()
{
this.message = null;
}
public String toString()
{
if (this.message == null)
{
return "Simple Interest Calculation Exception";
}
else
{
return "Simple Interest Calculation Exception : " + this.message;
}
}
public String getMessage()
{
return this.message;
}
}
class CompoundInterestCalculationException extends CustomException
{
String message;
CompoundInterestCalculationException(String message)
{
this.message = message;
}
CompoundInterestCalculationException()
{
this.message = null;
}
public String toString()
{
if (this.message == null)
{
return "Compound Interest Calculation Exception";
}
else
{
return "Compound Interest Calculation Exception : " + this.message;
}
}
public String getMessage()
{
return this.message;
}
}
class InterestCalculator implements SimpleInterestCalculator, CompoundInterestCalculator
{
private int principalAmount, rateOfInterest, time;
InterestCalculator()
{
this.principalAmount = 0;
this.rateOfInterest = 0;
this.time = 0;
}
InterestCalculator(int principalAmount, int rateOfInterest, int time)
{
this.principalAmount = principalAmount;
this.rateOfInterest = rateOfInterest;
this.time = time;
}
public void setPrincipalAmount(int principalAmount) throws SimpleInterestCalculationException
{
if (principalAmount < 0)
{
throw new SimpleInterestCalculationException("Principal Amount Cannot be Negative");
}
if (principalAmount == 0)
{
throw new SimpleInterestCalculationException("Principal Amount Cannot be Zero");
}
this.principalAmount = principalAmount;
}
public int getPrincipalAmount()
{
return this.principalAmount;
}
public void setRateOfInterest(int rateOfInterest) throws SimpleInterestCalculationException
{
if (rateOfInterest < 0)
{
throw new SimpleInterestCalculationException("Rate Of Interest Cannot be Negative");
}
if (rateOfInterest == 0)
{
throw new SimpleInterestCalculationException("Rate Of Interest Cannot be Zero");
}
this.rateOfInterest = rateOfInterest;
}
public int getRateOfInterest()
{
return this.rateOfInterest;
}
public void setTime(int time) throws SimpleInterestCalculationException
{
if (time < 0)
{
throw new SimpleInterestCalculationException("Time Cannot be Negative");
}
if (time == 0)
{
throw new SimpleInterestCalculationException("Time Cannot be Zero");
}
this.time = time;
}
public int getTime()
{
return this.time;
}
public int getSimpleInterest()
{
return (this.principalAmount * this.rateOfInterest * this.time) / 100;
}
public int getCompoundInterest()
{
int x, y, z;
x = (this.rateOfInterest / 100) + 1;
y = this.time;
z = 1;
while (y > 0)
{
z = z * x;
y--;
}
z = z * this.principalAmount;
return z;
}
}
class calculatepsp
{
public static void main(String gg[])
{
InterestCalculator simpleInterest = new InterestCalculator();
InterestCalculator compoundInterest = new InterestCalculator();
try
{
simpleInterest.setPrincipalAmount(-100);
simpleInterest.setRateOfInterest(5);
simpleInterest.setTime(2);
int simpleinterest = interestCalculator.getSimpleInterest();
System.out.println("Simple Interest : " + simpleinterest);
compoundInterest.setPrincipalAmount(1000);
compoundInterest.setRateOfInterest(-8);
compoundInterest.setTime(4);
int compoundinterest = interestCalculator.getCompoundInterest();
System.out.println("Compound Interest : " + compoundinterest);
}
catch (SimpleInterestCalculationException sice)
{
System.out.println(sice);
}
catch (CompoundInterestCalculationException cice)
{
System.out.println(cice);
}
}
}
I want to throw the exception of the class, if i am calculating simple interest then it should be SimpleInterestCalculationException and if i am calculating compound interest then it should be CompundInterestCalculationException.
Please Help Regarding this.
Three main options:
Make a base Exception, put it as throws on your method, make your other exceptions inherit from the base
Make multiple exceptions, use throws on your method as a comma delimted list, like public String myMethod() throws ExA, ExB, ExC
Make all your Exceptions extend Runnable, then you don't have to declare the throws (but it doesn't force your calling code to handle it either, so there is that)