Declaring generic variables with complex class in Java - java

I have a class to calculate with complex numbers, a real part and an imaginary part as double type.
In other part I have a rational class to calculate rational numbers.
Now I want that my complex class can operate when the real part and the imaginary part are rational numbers. I've read some docs about generics but I don't know how to declare real part and imaginary part as generic types and use methods as add 2 complex numbers when the real and imaginary parts are doubles or rationals.
This is my test code:
import java.util.regex.Pattern;
public class Complex {
private double real;
private double imaginary;
private Rational qreal;
private Rational qimaginary;
public Complex(double real, double imaginary) {
super();
this.real = real;
this.imaginary = imaginary;
}
public Complex(Rational real, Rational imaginary) {
this.qreal = real;
this.qimaginary = imaginary;
}
public Complex(String z) {
z = z.replaceAll(" ","");
if(z.contains("i") || z.contains("j")){
if(z.contains("+")) {
String[] z1 = z.split(Pattern.quote("+"));
this.real = Double.parseDouble(z1[0]);
this.imaginary = Double.parseDouble(z1[1].substring(0, z1.length-1));
}
else if(z.contains("-")) {
String[] z1 = z.split(Pattern.quote("-"));
this.real = Double.parseDouble(z1[0]);
this.imaginary = -Double.parseDouble(z1[1].substring(0, z1.length-1));
}
else System.out.println("Syntax Error");
}
else System.out.println("The complex must only contains i or j as imaginary unit");
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImaginary() {
return imaginary;
}
public Rational getQreal() {
return qreal;
}
public void setQreal(Rational qreal) {
this.qreal = qreal;
}
public Rational getQimaginary() {
return qimaginary;
}
public void setQimaginary(Rational qimaginary) {
this.qimaginary = qimaginary;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
Complex opposite(Complex z) {return new Complex(-z.real, -z.imaginary);}
double abs() {return Math.hypot(this.real, this.imaginary);}
Complex conjugate() {return new Complex(real, -imaginary);}
Complex inverse() {
if(this.real == 0 && this.imaginary == 0) return new Complex(Double.NaN, Double.NaN);
else {
Complex c = this.conjugate();
double abs_square = Math.pow(this.abs(), 2.);
return new Complex(c.real / abs_square, c.imaginary / abs_square);
}
}
Complex add2(Complex z) {
System.out.println("Suma " + this.qreal.add(z.qreal) + " " + this.qimaginary.add(z.qimaginary) + "i");
return new Complex(this.qreal.add(z.qreal), this.qimaginary.add(z.qimaginary));
}
Complex add(Complex z) {return new Complex(this.real + z.real, this.imaginary + z.imaginary);}
Complex subtract(Complex z) {return add(z.opposite(z));}
Complex product(Complex z) {
double r, i;
r = this.real * z.real - this.imaginary * z.imaginary;
i = this.real * z.imaginary + this.imaginary * z.real;
return new Complex(r, i);
}
Complex div(Complex z) {
Complex num = this.product(z.conjugate());
double den = Math.pow(Math.hypot(z.real, z.imaginary), 2.);
return new Complex(num.real / den, num.imaginary / den);
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Complex [real=" + real + ", imaginary=" + imaginary + ", qreal=" + qreal + ", qimaginary=" + qimaginary
+ "]";
}
/*#Override
public String toString() {
if(imaginary > 0.) {
if (imaginary == 1.)
return real + " + " + "i";
return real + " + " + imaginary + "i";
}
else if(imaginary < 0.) {
if (imaginary == -1.)
return real + " - " + "i";
return real + " " + imaginary + "i";
}
else if(imaginary == 0.)
return "" + real;
else if(real == 0.)
return imaginary + "i";
else
return "0";
}*/
}
If you see the code I've implemented 2 add methods but i want only one,and so that for the other methods, toString() too.

Generics are useful when you want to preserve type information. But the generic type still needs to have some known interface in order to use it. Since double and Rational don't share common interface, it will not be possible to directly create a generic implementation that works for both types.
What you could do is create an interface Complex with 2 implementations, DoubleComplex and RationalComplex:
public interface Complex<T> {
T getReal();
T getImaginary();
Complex<T> opposite(Complex<T> z);
double abs();
Complex<T> conjugate();
Complex<T> inverse();
Complex<T> add(Complex<T> z);
Complex<T> subtract(Complex<T> z);
Complex<T> product(Complex<T> z);
Complex<T> div(Complex<T> z);
}
public class DoubleComplex implements Complex<Double> {
private final double real;
private final double imaginary;
...
#Override
public Complex<Double> add(Complex<Double> z) {
return new DoubleComplex(this.real + z.getReal(), this.imaginary + z.getImaginary());
}
...
}
public class RationalComplex implements Complex<Rational> {
private final Rational real;
private final Rational imaginary;
...
#Override
public Complex<Rational> add(Complex<Rational> z) {
return new RationalComplex(this.real.add(z.getReal()), this.imaginary.add(z.getImaginary()));
}
...
}

Related

Java Interaction not returning

I'm making code in Java to put in numbers for variables a, b, c, and a label that calculates dimensions for a ellipsoid. Typing in Ellipsoid ex1 = new Ellipsoid ("Ex 1", 1, 2, 3); should give me the following in Interactions:
Ellipsoid "Ex 1" with axes a = 1.0, b = 2.0, c = 3.0 units has:
volume = 25.1327 cubic units
surface area = 48.9366 square units
But it gives me nothing. It's blank. I suspect that the last return statement at the bottom is coded wrong, but I can't figure out what exactly I'm doing wrong.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Ellipsoid {
private String label = " ";
private double a = 0;
private double b = 0;
private double c = 0;
public Ellipsoid(String labelIn, double aIn, double bIn, double cIn) {
setLabel(labelIn);
setA(aIn);
setB(aIn);
setC(cIn);
}
public String getLabel() {
return label;
}
public boolean setLabel(String labelIn) {
if(label != null) {
this.label = label.trim();
return true;
}
else {
return false;
}
}
public double getA() {
return a;
}
public boolean setA(double aIn) {
if(a > 0) {
this.a = a;
return true;
}
else {
return false;
}
}
public double getB(){
return b;
}
public boolean setB(double bIn) {
if (b > 0) {
this.b = b;
return true;
}
else {
return false;
}
}
public double getC() {
return c;
}
public boolean setC(double cIn) {
if(c > 0) {
this.c = c;
return true;
}
else {
return false;
}
}
public double volume() {
return (4 * Math.PI * a * b * c) / 3;
}
public double surfaceArea() {
double surfaceAreaDouble = (Math.pow((a * b), 1.6) + Math.pow((a * c), 1.6) + Math.pow((b * c), (1 / 1.6)) / 3);
surfaceAreaDouble = 4 * Math.PI * Math.pow(surfaceAreaDouble, (1 / 1.6));
return surfaceAreaDouble;
}
public String toString() {
DecimalFormat decimalFormat = new DecimalFormat("#,##0.0###");
return "Ellipsoid \"" + label + "\" with axes a = " + getA() + ", b = " + getB() + ", c = " +getC() + " units has:\n volume = " + decimalFormat.format(volume()) + " square units" + "\n surface area = " + decimalFormat.format(surfaceArea()) + " cubic units";
}
}
after looking at your code, I noticed the following issues:
In your setter methods you are not using the right variables. You should use the method parameters in all your setters.
example:
public boolean setA(double aIn) {
if(a > 0) { // a should be aIn here
this.a = a; // = a should be = aIn
return true;
}
else {
return false;
}
}
the surfaceArea() method has a small mistake:
(Math.pow((a * b), 1.6) + Math.pow((a * c), 1.6) + Math.pow((b * c), (1 / 1.6)) / 3);
The last one doesn't need the "1/ 1.6" part but just "1.6" like the rest and then you need another bracket for all 3 math.pow before you divide them by 3. (also switch "cubic" and "square" words to match volume and surface correct)
After these fixes, making an object of class Ellipsoid and printing it gives the output you are looking for:
public static void main(String[] args) {
Ellipsoid ex1 = new Ellipsoid ("Ex 1", 1, 2, 3);
System.out.println(ex1);
}
output:
Ellipsoid "Ex 1" with axes a = 1.0, b = 2.0, c = 3.0 units has:
volume = 25.1327 cubic units
surface area = 48.9366 square units

How to find center dots of given dots in radius of 16 (x;z)?

I'm trying to print out locations of center dots. Compared dots must be in radius of 16. Printing out only if there is more than 5 dots in one place calculating from center.
Center dot is, which is nearest to all nearby dots
My code is giving me false positives and duplicates. Methods:
HashMap<Location, HashSet<Location>> map = new HashMap<Location, HashSet<Location>>();
for (LocationCopy loc : locs) {
HashSet<LocationCopy> locsCopy = new HashSet<LocationCopy>(locs);
locsCopy.remove(loc);
for (LocationCopy loc2 : locsCopy) {
if (distance(loc2.getX(),loc.getX(),loc2.getZ(),loc.getZ()) <= 16) {
if (!map.containsKey(loc.getLoc())) {
HashSet<Location> hs = new HashSet<Location>();
hs.add(loc2.getLoc());
map.put(loc2.getLoc(), hs);
} else {
HashSet<Location> hs = map.get(loc.getLoc());
hs.add(loc2.getLoc());
map.put(loc2.getLoc(), hs);
}
}
}
}
for (Location loc : map.keySet()) {
if (map.get(loc).size() > 5) {
write("More than " + map.get(loc).size() + locToString(loc) + ": " + getLocs(map.get(loc)) + "<br>", fileName, beta);
}
}
private double distance(double x1, double x2, double z1, double z2){
return Math.sqrt(Math.pow(x2-x1,2)+Math.pow(z2-z1,2));
}
Class:
public class LocationCopy {
private int x, y, z;
private String world;
public LocationCopy(int x, int y, int z, String world) {
this.x = x;
this.y = y;
this.z = z;
this.world = world;
}
public LocationCopy(Location spawner) {
this.x = spawner.getBlockX();
this.y = spawner.getBlockY();
this.z = spawner.getBlockZ();
this.world = spawner.getWorld().getName();
}
public int getX(){
return x;
}
public int getZ(){
return z;
}
public Location getLoc() {
return new Location(Bukkit.getWorld(world), x, y, z);
}
}
There are serval small problems in your code:
map.put(loc2.getLoc(), hs); should be map.put(loc.getLoc(), hs); instead
You need to add a hashCode method to your classes, because otherwhise the HashSets you use will not be able to identify objects that represent the same location
You only search for groups of points, not for their centers
A solution could look like this (implemented your method in the class LocationCopy, because no class was shown in your question):
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class LocationCopy {
private int x, y, z;
//private String world;
public LocationCopy(int x/*, int y*/, int z/*, String world*/) {
this.x = x;
//this.y = y;
this.z = z;
//this.world = world;
}
public LocationCopy(Location spawner) {
this.x = spawner.getBlockX();
this.y = spawner.getBlockY();
this.z = spawner.getBlockZ();
//this.world = spawner.getWorld().getName();
}
//EDIT added toString method (just for better printing and debugging)
#Override
public String toString() {
return "LocationCopy [x=" + x + ", y=" + y + ", z=" + z + "]";
}
//EDIT: added hashCode method that is needed for the HashSets to identify objects that represent the same location
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
return result;
}
//EDIT: added equals method (not really needed, but better to have one...)
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LocationCopy other = (LocationCopy) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
if (z != other.z)
return false;
return true;
}
public int getX() {
return x;
}
public int getZ() {
return z;
}
public Location getLoc() {
return new Location(x, y, z);
}
public static void main(String[] args) {
List<LocationCopy> locs = createLocs();
HashMap<Location, HashSet<Location>> map = new HashMap<Location, HashSet<Location>>();
for (LocationCopy loc : locs) {
HashSet<LocationCopy> locsCopy = new HashSet<LocationCopy>(locs);
locsCopy.remove(loc);
for (LocationCopy loc2 : locsCopy) {
if (distance(loc2.getX(), loc.getX(), loc2.getZ(), loc.getZ()) <= 16) {
if (!map.containsKey(loc.getLoc())) {
HashSet<Location> hs = new HashSet<Location>();
hs.add(loc2.getLoc());
map.put(loc.getLoc(), hs);//EDIT: changed loc2 to loc
}
else {
HashSet<Location> hs = map.get(loc.getLoc());
hs.add(loc2.getLoc());
map.put(loc.getLoc(), hs);//EDIT: changed loc2 to loc
}
}
}
}
//EDIT: selecting groups for finding the center
Set<Set<Location>> groups = new HashSet<Set<Location>>();
for (Location loc : map.keySet()) {
if (map.get(loc).size() > 5) {
//EDIT: don't know what write does -> using System.out.println instead
//write("More than " + map.get(loc).size() + locToString(loc) + ": " + getLocs(map.get(loc)) + "<br>", fileName, beta);
System.out.println("More than " + map.get(loc).size() + " " + locToString(loc) + ": " + /*getLocs(map.get(loc)) + */"<br>");
//EDIT: create groups to find the center points
Set<Location> group = new HashSet<Location>();
group.addAll(map.get(loc));
group.add(loc);
groups.add(group);
}
}
//EDIT: find the center of the group
for (Set<Location> group : groups) {
Location center = findCenter(group);
System.out.println("center found: " + center);
}
}
/**
* Find the center of each group by calculating the summed distance from each point to every other point.
*
* The point that has the minimum summed distance to every other point is the center.
*/
private static Location findCenter(Set<Location> group) {
if (group.isEmpty()) {
throw new IllegalArgumentException("The group mussn't be empty");
}
List<LocationDistance> summedDistances = new ArrayList<LocationDistance>(group.size());
for (Location loc : group) {
LocationDistance dist = new LocationDistance(loc, 0);
//sum up the distance to each location in the group
for (Location loc2 : group) {
double distance = distance(loc.getBlockX(), loc2.getBlockX(), loc.getBlockZ(), loc2.getBlockZ());
dist.setDistance(dist.getDistance() + distance);
}
summedDistances.add(dist);
}
//sort the list (LocationDistance implements Comparable to do this)
Collections.sort(summedDistances);
//the first item in the list is the center
return summedDistances.get(0).getLocation();
}
private static List<LocationCopy> createLocs() {
List<LocationCopy> locs = new ArrayList<LocationCopy>();
//trying to create the example from the image in your question
locs.add(new LocationCopy(0, 0));
locs.add(new LocationCopy(2, 0));
locs.add(new LocationCopy(5, 0));
locs.add(new LocationCopy(1, 2));
locs.add(new LocationCopy(2, 1));//center
locs.add(new LocationCopy(4, 1));
locs.add(new LocationCopy(3, 2));//adding a new point because otherwhise it will never be enough for a group greater than 5
locs.add(new LocationCopy(10, 30));
locs.add(new LocationCopy(12, 31));
locs.add(new LocationCopy(15, 31));
locs.add(new LocationCopy(8, 36));
locs.add(new LocationCopy(13, 33));//center
locs.add(new LocationCopy(18, 34));
locs.add(new LocationCopy(15, 36));//adding a new point because otherwhise it will never be enough for a group greater than 5
return locs;
}
private static String locToString(Location loc) {
return loc.getBlockX() + " " + loc.getBlockY() + " " + loc.getBlockZ();
}
private static double distance(double x1, double x2, double z1, double z2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(z2 - z1, 2));
}
}
The class Location (the important part is the hashCode method):
public class Location {
public int x, y, z;
public Location(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getBlockX() {
return x;
}
public int getBlockY() {
return y;
}
public int getBlockZ() {
return z;
}
#Override
public String toString() {
return "Location [x=" + x + ", y=" + y + ", z=" + z + "]";
}
//EDIT here the hashCode is also important for the HashSets you use in your code
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
result = prime * result + z;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Location other = (Location) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
if (z != other.z)
return false;
return true;
}
}
and a new class LocationDistance for comparing distances:
/**
* A class for comparing the distances for locations
*/
public class LocationDistance implements Comparable<LocationDistance> {
private Location location;
private double distance;
public LocationDistance(Location location, double distance) {
this.location = location;
this.distance = distance;
}
#Override
public String toString() {
return "LocationDistance [location=" + location + ", distance=" + distance + "]";
}
#Override
public int compareTo(LocationDistance other) {
return Double.compare(distance, other.getDistance());
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
}
The output is:
More than 6 2 0 0: <br>
More than 6 1 0 2: <br>
More than 6 2 0 1: <br>
More than 6 5 0 0: <br>
More than 6 4 0 1: <br>
More than 6 3 0 2: <br>
More than 6 10 0 30: <br>
More than 6 12 0 31: <br>
More than 6 8 0 36: <br>
More than 6 15 0 31: <br>
More than 6 13 0 33: <br>
More than 6 15 0 36: <br>
More than 6 18 0 34: <br>
More than 6 0 0 0: <br>
center found: Location [x=2, y=0, z=1]
center found: Location [x=13, y=0, z=33]
Here the last two lines are the centers you were searching for.

Java Rational Lab

I cant seem to figure out what's wrong with my code. I commented out the reduce() method to see if it would work with the unreduced fractions (I don't think my reduce() works) and for the first ones it does work, but when it gets to double digits and the later ones I cant figure out why it isn't working.
public class Rational implements Comparable<Rational> {
private int numerator, denominator;
public Rational() { numerator = 1; denominator = 1; }
public Rational(int num, int denom) { numerator = num; denominator = denom; }
public void setRational(int num, int denom) { setNumerator(num); setDenominator(denom); }
public void setNumerator(int num) { numerator = num; }
public void setDenominator(int denom) { denominator = denom; }
public int getNumerator() { return numerator; }
public int getDenominator() { return denominator; }
public void reduce() {
setNumerator(this.numerator / gcd(this.numerator, this.denominator));
setDenominator(this.denominator / gcd(this.numerator, this.denominator));
}
public int gcd(int num1, int num2) {
if (num2 == 0) return num1;
return gcd(num2,num1 % num2);
}
public Object clone() { return new Rational(getNumerator(), getDenominator()); }
public boolean equals(Object obj){ return this.compareTo((Rational)obj) == 0; }
public void add(Rational other) {
this.setNumerator( (this.getNumerator() * other.denominator ) + ( other.numerator * this.getDenominator() ));
this.setDenominator( this.getDenominator() * other.denominator );
//reduce();
}
public void sub(Rational other) {
numerator = ( this.getNumerator() * other.getDenominator() ) - ( other.getNumerator() * this.getDenominator() );
denominator = ( this.getDenominator() * other.getDenominator() );
//reduce();
}
public void mult(Rational other) {
numerator = ( this.getNumerator() * other.getNumerator() );
denominator = ( this.getDenominator() * other.getDenominator() );
//reduce();
}
public void div(Rational other) {
numerator = (this.getNumerator() * other.getDenominator());
denominator = (this.getDenominator() * other.getNumerator());
//reduce();
}
public int compareTo(Rational other) {
reduce();
other.reduce();
if ( this.getDenominator() < other.getDenominator() ) {
return -1;
}
else if ( this.getDenominator() == other.getDenominator() ) {
if( this.getNumerator() < other.getNumerator() ) {
return -1;
}
else if( this.getNumerator() > other.getNumerator() ) {
return 1;
}
else return 0;
}
else return 1;
}
public String toString() {
return this.numerator + "/" + this.denominator + "\n";
}
}
this is the runner
import static java.lang.System.out;
public class RationalRunner {
public static void main(String args[]) {
Rational test = new Rational();
out.println("test = " + test);
Rational newOne = new Rational(3, 4);
out.println("newOne = " + newOne);
out.println("test.equals(newOne) = " + test.equals(newOne));
newOne = (Rational) test.clone();
out.println("\n\nnewOne after test.clone() = " + newOne);
out.println("test.equals(newOne) = " + test.equals(newOne));
Rational rOne = new Rational(1, 2);
Rational rTwo = new Rational(2, 3);
out.println("1/2.equals(2/3) = " + rOne.equals(rTwo));
test.setRational(4, 6);
out.println("2/3.equals(4/6) = " + rTwo.equals(test));
out.println("\n\nrOne = " + rOne);
out.println("rTwo = " + rTwo);
out.println("rOne.compareTo(rTwo) = " + rOne.compareTo(rTwo));
out.println("rTwo.compareTo(rOne) = " + rTwo.compareTo(rOne));
rOne.add(rTwo);
out.println("\n\nrOne.add(rTwo) = " + rOne);
rOne.setRational(1, 2);
rTwo.setRational(1, 3);
rOne.add(rTwo);
out.println("\n\n1/2.add(1/3) = " + rOne);
rOne.setRational(4, 10);
rTwo.setRational(3, 5);
rOne.add(rTwo);
out.println("\n\n4/10.add(3/5) = " + rOne);
rOne.setRational(2, 10);
rTwo.setRational(3, 6);
rOne.add(rTwo);
out.println("\n\n2/10.add(3/6) = " + rOne);
//1/4 + 2/8 = 1/2
rOne.setRational(1, 4);
rTwo.setRational(2, 8);
out.println("\n\n1/4.equals(2/8) = " + rOne.equals(rTwo));
rOne.add(rTwo);
out.println("\n\n1/4.add(2/8) = " + rOne);
//1/6 + 2/8 = 5/12
rOne.setRational(1, 6);
rTwo.setRational(2, 8);
out.println("\n\n1/6.equals(2/8) = " + rOne.equals(rTwo));
rOne.add(rTwo);
out.println("\n\n1/6.add(2/8) = " + rOne);
}
}
For example, when you set one of them to 1/6 and 2/8, it comes up with 14/48 when it should be 20/48. I have tried retyping the add method and trying a different way, but it still comes out with the 14/48, im not sure why
As your example, when i comment out .equals() method, it return the correct value.
So, i check your .compareTo() method and find out, you reduce on raw data. It's means after compare, the value of rOne and rTwo was modified.
You should clone object and calculate on them
Rational num1 = new Rational(numerator, denominator);
Rational num2 = new Rational(other.getNumerator(), other.getDenominator());
I've correct them:
public int compareTo(Rational other) {
//Should create copy constructor
Rational num1 = new Rational(numerator, denominator);
Rational num2 = new Rational(other.getNumerator(), other.getDenominator());
num1.reduce();
num2.reduce();
if (num1.getDenominator() < num2.getDenominator()) {
return -1;
} else if (num1.getDenominator() == num2.getDenominator()) {
if (num1.getNumerator() < num2.getNumerator()) {
return -1;
} else if (num1.getNumerator() > num2.getNumerator()) {
return 1;
} else {
return 0;
}
} else {
return 1;
}
}
P/s: I just check with your example. So any calculator is wrong, you can correct on the same way.

Trying to set values in a second class for overload methods in first class?

I am new to java and am currently creating a program where I calculate various amounts of money (tax, gross pay, etc) using overload methods and then display it. I have completed the bulk of it (I think), but now I need to create a second class in the same package where I set values to the first program to see if it works. I have no idea how to call the method when overload methods are involved, I tried to use get and set but I don't know how to apply that in the overload method. I apologize if my terminology is off, I'm still quite new!
package payrolllibrary;
public class PayrollLibrary {
public static float calculatePay(float hours, float rates)
{System.out.println("Pay: " + rates*hours);
return 0;
}
public static float calculatePay(float hours, float rates, float multiplier)
{System.out.println("Pay: " + rates*hours*multiplier);
return 0;
}
public static float calculateGrossPay(float regularPay, float overtimePay, float shift2Pay, float shift3Pay, float weeklyPay)
{float grossPay;
grossPay = regularPay + overtimePay + shift2Pay + shift3Pay + weeklyPay;
System.out.println("Gross Pay: " + grossPay);
return 0;
}
public static float calculatedSocialSecurityTax(float grossPay, float ytdEarnings, float ytdSocialSecurity)
{
float calculateSocialSecurityTax = 0;
float calculateGrossPay = 0;
if(ytdEarnings > 118500)
{calculateSocialSecurityTax = 0;}
if (ytdEarnings+calculateGrossPay < 118500)
{calculateSocialSecurityTax = calculateGrossPay*.062f;}
if (ytdEarnings+calculateGrossPay > 118500)
{if (calculateGrossPay*.062 <= 118500)
{calculateSocialSecurityTax = 118500;}
}
{System.out.println("Social Security Tax: " + calculateSocialSecurityTax);
return 0;
}
}
public static float calculateMedicareTax(float grossPay)
{float medicareTax;
medicareTax = grossPay*.0145f;
System.out.println("Medicare Tax: " + medicareTax);
return 0;
}
public static float calculateStateTax(float grossPay, float stateWithholding)
{System.out.println("State Tax: " + grossPay*stateWithholding);
return 0;
}
public static float calculateNetPay(float grossPay, float federalWithholding, float socialSecurityWithholding, float medicareWithholding, float stateWithholding, float deduction1Amount, float deduction2Amount, float deduction3Amount)
{float calculateNetPay;
calculateNetPay = grossPay-federalWithholding-socialSecurityWithholding-medicareWithholding-stateWithholding-deduction1Amount-deduction2Amount-deduction3Amount;
System.out.println("Net Pay: " + calculateNetPay);
return 0;
}
public static float calculateDeduction(float grossPay, char deductionCode, float deductionValue)
{if (deductionCode == 'N')
{deductionValue = 0;}
else if (deductionCode == 'F')
{deductionValue = deductionValue;}
else if (deductionCode == 'P')
{deductionValue = deductionValue*grossPay;}
System.out.println("Deduction: " + deductionValue);
return 0;
}
}
package PayrollLibrary;
public class TestPayroll {
public static void main(String[] args) {
PayrollLibrary Person = new PayrollLibrary();
Person.setRate(99.99);
Person.setHours(99);
Person.setMultiplier(999);
Person.setRegularPay(999);
Person.setOvertimePay(999);
Person.setShift2Pay(999);
Person.setShift3Pay(999);
Person.setWeekendPay(999);
Person.setYtdEarnings(999);
Person.setYtdSocialSecurity(999);
Person.setStateWithholding(999);
Person.setDeduction1Amount(999);
Person.setDeduction2Amount(999);
Person.setDeduction3Amount(999);
Person.setDeductionCode('F');
Person.setDeductionAmount(999);
}
}
Those setXXX() won't set the values just because their English meaning are so. They are just names of methods. To set the values you have to code them. So in your PayrollLibrary you should have
public class PayrollLibrary {
float rate;
float hours;
......
public void setRate(float inRate) {
this.rate = inRate;
}
public void setHours(float inHours) {
this.hours = inHours;
}
Then in your calculation methods, if what you going to use are rate and hours, you don't have to pass them to the method, simply:
public float calculatePay() {
return rate*hours;
}
So in your main(), do this:
PayrollLibrary person = new PayrollLibrary();
person.setRate(99.99f);
person.setHours(99.0f);
to obtain the pay right after the setXXX above, do this:
float thePay = person.calculatePay();
Please note the Java convention: class names starts in upper case, variable and method names start in lower case.
Hope it helps.

Fan prob with toString() method -- Simple [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am trying to create a program where you can change a fans speed, color, radius, and whether you can turn the fan on or off, I have the fan class working fine, except for the toString() method, for some reason when I set some values in the test program, it just defaults to the regular values, any help is accepted.
Thank you.
public class Fan {
final int SLOW = 1;
final int MEDIUM = 2;
final int FAST = 3;
public int speed = SLOW;
public boolean on = false;
public double radius = 5;
public String color = new String("blue");
//fan on
boolean fanOn() {
on = true;
return on;
}
//fan off
boolean fanOff() {
on = false;
return on;
}
//sets fan speed
String setSpeed(String speed) {
if (speed == "SLOW"){
speed = String.valueOf(SLOW);
} else if (speed == "MEDIUM") {
speed = String.valueOf(MEDIUM);
} else if (speed == "FAST") {
speed = String.valueOf(FAST);
} else {
speed = "Please enter 'SLOW', 'MEDIUM' or 'FAST' to change the speed of the fan.";
}
return speed;
}
//sets custom radius
double setRadius(double rad) {
rad = radius;
return rad;
}
//sets custom color
String setColor(String colorType) {
return colorType;
}
//toString() method
public String toString() {
return ("Speed: " + speed + "\nRadius: " + radius + "\nColor: " + "\nOn: " + on);
}
}
//test program
public class TestFan {
public static void main(String[] args) {
Fan fan1 = new Fan();
fan1.setColor("green");
fan1.setSpeed("FAST");
fan1.setRadius(3.5);
fan1.fanOff();
System.out.println(fan1.toString());
}
}
This just outputs:
Speed: 1
Radius: 5.0
Color:
On: false
public class Fan {
final int SLOW = 1;
final int MEDIUM = 2;
final int FAST = 3;
public int speed = SLOW;
public boolean on = false;
public double radius = 5;
public String color = new String("blue");
//fan on
void fanOn() {
on = true;
return on;
}
//fan off
void fanOff() {
on = false;
return on;
}
//sets fan speed
void setSpeed(String speed) {
this.speed=speed;
}
//sets custom radius
double setRadius(double rad) {
rad = radius;
return rad;
}
//sets custom color
void setColor(String colorType) {
color = colorType;
}
//toString() method
public String toString() {
return ("Speed: " + speed + "\nRadius: " + radius + "\nColor: " + "\nOn: " + on);
}
}
//test program
public class TestFan {
public static void main(String[] args) {
Fan fan1 = new Fan();
fan1.setColor("green");
fan1.setSpeed("FAST");
fan1.setRadius(3.5);
fan1.fanOff();
System.out.println(fan1.toString());
}
}

Categories