Not sure if I'm doing this right, but this is a continuation of the program I was working on here...Homework Help PT1
I'm struggling a lot with this homework assignment...
**(Math: The Complex class) A complex number is a number in the form a + bi,
where a and b are real numbers and i is 2-1. The numbers a and b are known
as the real part and imaginary part of the complex number, respectively. You can
perform addition, subtraction, multiplication, and division for complex numbers
using the following formulas:
a + bi + c + di = (a + c) + (b + d)i
a + bi - (c + di) = (a - c) + (b - d)i
(a + bi)*(c + di) = (ac - bd) + (bc + ad)i
(a + bi)/(c + di) = (ac + bd)/(c2 + d2) + (bc - ad)i/(c2 + d2)
You can also obtain the absolute value for a complex number using the following
formula:
a + bi = 2a2 + b2
Design a class named Complex for representing complex numbers and the
methods add, subtract, multiply, divide, and abs for performing complexnumber
operations, and override toString method for returning a string representation
for a complex number. The toString method returns (a + bi) as a
string. If b is 0, it simply returns a. Your Complex class should also implement the
Cloneable interface.
Provide three constructors Complex(a, b), Complex(a), and Complex().
Complex() creates a Complex object for number 0 and Complex(a) creates
a Complex object with 0 for b. Also provide the getRealPart() and
getImaginaryPart() methods for returning the real and imaginary part of the
complex number, respectively.
Write a test program that prompts the user to enter two complex numbers and
displays the result of their addition, subtraction, multiplication, division, and absolute
value.**
Here is what I have so far. Two classes...
// ComplexTest.java
import java.util.Scanner;
public class ComplexTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the first complex number: ");
double realPart = input.nextDouble();
System.out.println("Enter the second complex number: ");
double imaginaryPart = input.nextDouble();
Complex cn1 = new Complex(realPart, imaginaryPart);
Complex cn2 = new Complex(realPart);
Complex cn3 = new Complex();
if (realPart == 0) {
System.out.println(cn3.toString());
}
if (imaginaryPart == 0) {
System.out.println(cn2.toString());
}
if(realPart != 0 && imaginaryPart != 0) {
System.out.println(cn1.toString());
}
}
}
// Complex.java
import java.util.Scanner;
public class Complex {
// cloneable interface
public interface Cloneable { }
// Instance Real + Getters and Setters (Accessors and Mutators)
private double realPart;
public double getReal() {
return realPart;
}
public void setReal(double real) {
this.realPart = real;
}
// Instance Real + Getters and Setters (Accessors and Mutators)
private double imaginaryPart;
public double getImaginary() {
return imaginaryPart;
}
public void setImaginary(double imaginary) {
this.imaginaryPart = imaginary;
}
// Constructor Method CN1
public Complex(double a, double b) {
realPart = a;
imaginaryPart = b;
}
// Constructor Method CN2
public Complex(double a) {
realPart = a;
imaginaryPart = 0;
}
// Constructor Method CN3
public Complex() { }
// Add Complex Numbers
public Complex add(Complex comp1, Complex comp2) {
double real1 = comp1.getReal();
double real2 = comp2.getReal();
double imaginary1 = comp1.getImaginary();
double imaginary2 = comp2.getImaginary();
return new Complex(real1 + real2, imaginary1 + imaginary2);
}
// Subtract Complex Numbers
public Complex subtract(Complex comp1, Complex comp2) {
double real1 = comp1.getReal();
double real2 = comp2.getReal();
double imaginary1 = comp1.getReal();
double imaginary2 = comp2.getReal();
return new Complex(real1 - real2, imaginary1 - imaginary2);
}
// Multiply Complex Numbers
public Complex multiply(Complex comp1, Complex comp2) {
double real1 = comp1.getReal();
double real2 = comp2.getReal();
double imaginary1 = comp1.getReal();
double imaginary2 = comp2.getReal();
return new Complex(real1 * real2, imaginary1 * imaginary2);
}
// Divide Complex Numbers
public Complex divide(Complex comp1, Complex comp2) {
double real1 = comp1.getReal();
double real2 = comp2.getReal();
double imaginary1 = comp1.getReal();
double imaginary2 = comp2.getReal();
return new Complex(real1 / real2, imaginary1 / imaginary2);
}
// toString to Change Display
public String toString() {
String result;
result = realPart + " + " + imaginaryPart + "i";
return result;
}
}
Here is my updated code after Jan's help. I've created 3 more methods (subtract, multiply and divide). Should I not be using comp1 and comp2 in every method and instead name them separately from each other? The goal is to print the results of each method at the end at the same time. Will these having the same names mess with that?
I'd also like to know when I should implement the cloneable interface.
Lastly, according to the text a complex number actually looks like two numbers separated by a space. (i.e. 3.5 5.0 rather than just 3.5). If I add two more scanner inputs for the second halves of both of complex numbers, I will have to change my code. Will I have to create new getters and setters to receive this number? Such as imaginaryPart2 and realPart2?
Thank you again for all of the help.
Some Topics to dwell upon:
Variable Scope
Parameters passed into a method are visible only throughout that method. So naming your two operands comp1 and comp2 for each and all of your methods is perfectly fine.
But:
Object Orientation
Your methods should only have one parameter. Say your have one instance of Complex named x. And you want to add to that another instance named y. Then given your code, any operation of x.add(x,y) and y.add(x,y) and even z.add(x, y) would yield the same results.
So: Drop one of your paramters. You might want to add nullchecks.
public Complex add(Complex toAdd) {
return new Complex(this.realPart + toAdd.realPart,
this.imaginaryPart + toAdd.imagineryPart);
}
Now you can write
Complex z = x.add(y);
Getters and Setters
As your add / subtract / divide / multiply operations all return a new Complex number, you might want to make Contex immutable - that is: Provide no setters. Complex number can be created through the constructors. You can get new Complex numbers by invoking calculations on existing ones. But you cannot change a number.
So my advice: Remove the setters.
Input of complex numbers
Instead of reading doubles, you might want to think about reading a String and match that string with a regular expression. You could use that as a utility method in your main or even as a consttructor for Complex, allowing to use a String as input.
Consider this method for matching String:
Pattern complexFinder = Pattern.compile("(-?\\d+(\\.\\d*)?)?\\s*([-+]\\s*\\d+(\\.\\d*)?i)?");
Matcher m = complexFinder.matcher(complexString);
if (m.find()) {
double realPart = 0;
double imaginaryPart = 0;
if (m.group(1) != null) {
realPart = Double.parseDouble(m.group(1).replaceAll("\\s", ""));
}
if (m.group(3) != null) {
imaginaryPart = Double.parseDouble(m.group(3).replaceAll("\\s", "").replace("i", ""));
}
Complex c = new Complex(realPart, imaginaryPart);
}
Cloneable
Cloneable is an interface you add to your class declaration:
public class Complex implements Cloneable {
Additionally you should implement a clone() method:
public Object clone() {
return super.clone();
}
toString()
Your assignment requests that an 0 imaginary part be left out in String output. So you might want to check that again. This should be a simple if()
Related
Your task is to create a class that will model a complex number.
A complex number is a number of the form a + bi, where a is the “real”
part and b is the “imaginary” part. It is based on the mathematical
premise that i2 = -1. So like the fraction class, you will define two
double data members for real and imaginary.
I will be pulling from a driver file that my professor has supplied to us. I am having no issues compiling, however am having issues running my program. I am getting a popup window from JGrasp that states "No Main methods, Java FX applications, applets, or midlets found in file.". I'm assuming that I need to put a main method into my created class however I am not sure where to put it or how to label/define it. Can someone guide me to solve this?
Thank you, my code is below.
class Complex {
private double real;
private double imaginary;
final double LIMIT = 10;// final means that this object stays the same for all.
Complex() {//constructors (there are 3, progressing in size)
real = 0;
imaginary = 0;
}
Complex(double actual) {// parameter calls what I'm assigning real to
this.real = actual;
imaginary = 0;
}
Complex(double actual, double fake) {
this.real = actual;
this.imaginary = fake;
}
public double getReal() {//accessors (there are 2, one for each parameter)
return real;
}
public double getImaginary() {
return imaginary;
}
public void setReal(double actual) {// sets real to actual, mutator.
this.real = actual;
}
public void setImaginary(double fake) {// sets imaginary to fake, mutator.
this.imaginary = fake;
}
public String toString() {//returns a String neatly in the form a + bi
return real + " " + imaginary + "i";
}
public boolean equals(Complex complexNumber) {
if(real == complexNumber.real && imaginary == complexNumber.imaginary) {//takes a complex number as a parameter type and
//returns a boolean of true if the calling object is equal to the parameter.
return true;
}
else {
return false;
}
}
public Complex add(Complex complexNumber) {
Complex temp = new Complex (0.0,0.0);
temp.real = real + complexNumber.real;
temp.imaginary = imaginary + complexNumber.imaginary;
return temp;
}
public Complex add (double val) {
Complex temp = new Complex(0.0, 0.0);
temp.real = real + val;
temp.imaginary = imaginary + val;
return temp;
}
// Override method to add fist parameter Complex object value with second Complex parameter object value
public static Complex add(Complex complexNumber, Complex c2) {
Complex temp = new Complex(0.0, 0.0);
temp.real = complexNumber.real + c2.real;
temp.imaginary = complexNumber.imaginary + c2.imaginary;
return temp;
}// End of method
// Method to check the size of implicit Complex object is greater than the LIMIT
// If greater than return true
// Otherwise return false
public boolean isBig() {
// Calculates size
double size = Math.sqrt((Math.pow(real, 2) + Math.pow(imaginary, 2)));
// Checks if size is greater than LIMIT return true
if(size > LIMIT)
return true;
// Otherwise not big return false
else
return false;
}// End of method
} // End of class
You should not put the main method of the application in this class, but a separate one, e.g. App, in the same package or higher in the package hierarchy, with a body like
public class App {
public static void main(String[] args){
System.out.println(new Complex(0.1, 0.2));
}
}
Create a program which simulates a very simple calculator
So I have been asked to implement an abstract class that represents binary (having 2 arguments) arithmetic expression
abstract class ArithmeticExpression {
double binary1;
double binary2;
public abstract void evaluate ();
public abstract void display ();
}
so then I created sub classes add, multiply, subtract, and divide. In subtract I have:
public class subtract extends ArithmeticExpression {
// private double result;
double binary1;
double binary2;
public subtract (double x, double y) {
this.binary1 = x;
this.binary2 = y;
}
public void evaluate () {
System.out.println("Expression: " + getsubX() + " - " + getsubY() + " = ");
// return result;
}
public void display () {
}
public double getsubX() {
}
public double getsubY() {
}
Using the classes I should be able to represent any arbitrary expression, with no hard coding.
It is also said evaluate should return the result as double and display method should print the expression out in string. Am I on the right track? What am I missing here? The part I do not understand how it is able to represent any expression?
Using your abstract ArithmeticExpression, here's what the Subtract class should look like. Java classes start with a capital letter.
public class Subtract extends ArithmeticExpression {
double result;
public Subtract(double x, double y) {
this.binary1 = x;
this.binary2 = y;
}
#Override
public void evaluate() {
result = binary1 - binary2;
}
#Override
public void display() {
System.out.println("Expression: " + binary1 +
" - " + binary2 + " = " + result);
}
}
You don't have to re-declare binary1 and binary2. They are instantiated in the abstract ArithmeticExpression class.
You do have to provide a double for the result. This should have been done in the abstract ArithmeticExpression class.
The evaluate() method is for evaluation.
The display() method is for display.
You don't have to define any other methods in your Subtract concrete class.
If you want to evaluate any expession inserted in form of
4 + 3 * ( 4 + 5)
You either need to create binary tree or stack and fill those values and operators in.
What I quite dont understand is your so called binary represented in double. If you want to have binary calc, you should use unsigned int or long (or any other type, that is not floating point)
Well, I need to make a project where I have two interfaces and they are both used in two unrelated classes. I managed to get everything else to work out properly except for the compareTo method. The two classes I have made are Car and Horse. What I am trying to do is compare the milesGoal from Horse to the one in Car and return either a 1, 0, or -1.
However when I try doing this I get the error "double could not be dereferenced"
I have been stuck on this for a while trying to find different ways to approach this part of the code. I tried using compareTo in the tester class instead of making a method but I got the same error and I am required to make it into a method.
This is the Horse Class:
public class Horse implements milesInterface , kilometersInterface{
private double currentMile;
private double currentKilo;
private double milesGoal;
private double kilosGoal;
private String horseBreed;
// CONSTRUCTORS
public Horse(){
currentMile = 0;
currentKilo = 0;
milesGoal = 0;
kilosGoal = 0;
horseBreed = "Unspecified";
}
public Horse(double cm, double ck, double mg, double kg, String hb){
currentMile = cm;
currentKilo = ck;
milesGoal = mg;
kilosGoal = kg;
horseBreed = hb;
}
// MILE METHODS
public double remainingMiles(){ // Finds the remaining miles
return milesGoal-currentMile;
}
public void halfMile(){ // Divides the desired goal halfway (Miles)
milesGoal = milesGoal/2;
}
public void setMileGoal(double newMile){ // Allows you to set a new goal
milesGoal = newMile;
}
public double getMileGoal(){
return milesGoal;
}
// KILOMETER METHODS
public double remainingKilos(){ // Finds the remaining Kilos
return kilosGoal-currentKilo;
}
public void halfKilo(){ // Divides the desire goal halfway (Kilos)
kilosGoal = kilosGoal/2;
}
public void setKiloGoal(){ // Allows you to set a new goal
kilosGoal = milesGoal*1.6;
}
public void setCurrentKilo(){ // Allows you to set the current Kilo
currentKilo = currentMile * 1.6;
}
// UNIQUE METHODS
public double getMilesStatus(){
return currentMile;
}
public double getKilosStatus(){
return currentKilo;
}
public String getHorseBreed(){
return horseBreed;
}
public void convertToKilos(){ // Converts current miles to kilometers
double kilos = currentMile * 1.6;
System.out.println("The current miles to kilometers is: " + kilos + "km.");
}
public void convertToMiles(){ // Converts current kilometers to miles
double miles = currentKilo * .6;
System.out.println("The current kilometers to miles is: " + miles + "m.");
}
public void milesPerHour(double hours){ // Calculates the mph to the goal by a time
double answer = milesGoal / hours;
System.out.println("The mph needed to reach the desination in " + hours + " hours: " + answer);
}
public void kilosPerHour(double hours){ // Calculates the kmph to the goal by a time
double answer = kilosGoal / hours;
System.out.println("The kilometers needed to reach the desination in " + hours + " hours: " + answer);
}
public int compareTo(Object Other){
if(milesGoal > (Horse)milesGoal.Other)
return 1;
if(milesGoal < (Horse)milesGoal.Other)
return 0;
return -1;
}
}
The Car class is pretty much the same as the Horse one and I need to find a way to compare both of their milesGoal to see which one is greater. I tried multiple things but it doesn't seem to work
This is the interface I made:
abstract interface milesInterface{
public double remainingMiles();
public void halfMile();
public void setMileGoal(double newMile);
public int compareTo(Object Other);
}
abstract interface kilometersInterface{
public double remainingKilos();
public void halfKilo();
public void setCurrentKilo();
public int compareTo(Object Other);
}
First, you are writting attribute.object. This is what fails. Other.milesGoal is a better option.
Another problema is with the casting. What you are doing is trying to cast milesGoal.other to Horse (you want to cast milesGoal)
You should use
if (milesGoal > ((Horse) other).milesGoal)
Also, use proper capitalization (variables go in lowercase, clases/interfaces in uppercase) and setters and getters.
Additionally, you probably will want to cast to the interface so you can use the methods with other clases that implement it
if (milesGoal > ((MilesInterface) other).milesGoal)
Firstly, (Horse)milesGoal.Other should be ((Horse) Other).milesGoal.
I would suggest overloading compareTo with one method for comparing to Horses and one method for comparing to Cars. Then your code looks like
public int compareTo(Horse horse){
if(milesGoal > horse.milesGoal)
return 1;
if(milesGoal < horse.milesGoal)
return -1;
return 0;
}
public int compareTo(Car car){
if(milesGoal > car.milesGoal)
return 1;
if(milesGoal < car.milesGoal)
return -1;
return 0;
}
first i would like to start saying that i am new to programing and i don t know much. with that said i would appreciate if anyone could help me with my program that it is supposed to read 2 fractions and an operator for example "2/3 + 4/5". i have some of the code done but it still give me an error when i run it here is what i have so far:
public class Fraction {
private static int numer;
private static int denom;
public Fraction(int num, int den)
{
numer = num;
denom = den;
simplify();
}
int findGcd(int a, int b)
{
int temp;
while(b != 0)
{
temp = b;
b = a % b;
a = temp;
}
return a;
}
void simplify()
{
int gcd = findGcd(numer, denom);
numer /= gcd;
denom /= gcd;
}
public int getNumer(){
return numer;
}
public int getDenom(){
return denom;
}
Fraction add(Fraction x) {
Fraction result;
if (x.getDenom()== getDenom()) {
result = new Fraction(x.getNumer() + getNumer(), denom);
} else {
denom = this.getDenom() * x.getDenom();
numer = this.getNumer() * x.getDenom() + x.getNumer() * this.getDenom();
return new Fraction(numer,denom);
}
return result;
}
public String toString(){
return (Integer.toString(numer) + "/" +
Integer.toString(denom));
}
public static void main (String []args){
Fraction a = new Fraction(1,3);
Fraction b = new Fraction(4,5);
System.out.println(a.toString());
System.out.println(b.toString());
}
}
thank you for your help i really appreciate it.
Why are you making your fields static? static fields belong to the class as opposed to each instantiation (not what you want here). Try removing the static keyword.
On another note, you mentioned that you'd like to read input from the user. You might want to look into using a Scanner for this (in case you don't already know about this handy class).
Once you read the input, something like 2/3 + 4/5, you can split your string using a space as your delimiter. Now, you can parse a fraction from the first (2/3) and third (4/5) elements of the newly formed string array, and perform the operation that corresponds to the second element of the array (+).
There is a difference between static variable and instance variable.
Static variable is a class variable which is common for all instances.. So, if you change these variables for one instance, it will be changed for all the instances.
Instance variable, on the other hand, are specific to each instance.. They are binded to an instance of a class.
That being said.. You need to modify your code a little bit..
Change your static variables in your class to instance variables..
private static int numer;
private static int denom;
The above two variables should be instance variables.. So that they are unique for each instance you create for your class..
So, change them to: -
private int numer;
private int denom;
And for reading user input, A.R.S has already given you link to a valuable class..
999 to 999
1000 to 1k
1500000 to 1.5m
and so on, I would like to not lose any precision at all
Also, need to convert them back to their original value
1.5m to 1500000
etc
The highest it would go is 11 digits max
Thanks
How about this:
import static java.lang.Double.parseDouble;
import static java.util.regex.Pattern.compile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
private static final Pattern REGEX = compile("(\\d+(?:\\.\\d+)?)([KMG]?)");
private static final String[] KMG = new String[] {"", "K", "M", "G"};
static String formatDbl(double d) {
int i = 0;
while (d >= 1000) { i++; d /= 1000; }
return d + KMG[i];
}
static double parseDbl(String s) {
final Matcher m = REGEX.matcher(s);
if (!m.matches()) throw new RuntimeException("Invalid number format " + s);
int i = 0;
long scale = 1;
while (!m.group(2).equals(KMG[i])) { i++; scale *= 1000; }
return parseDouble(m.group(1)) * scale;
}
If they weren't final you could extend java.lang.Integer etc. to override the toString() method. Is it worth creating a java.lang.Number subclass? Probably not. You could create your own classes: MyInteger, MyFloat etc using composition (they'll have an attribute to hold the numeric value) and override the toString() method to return the formats you want.
For the other way around, you could create factory methods in your MyXXX classes that creates objects containing the numeric value of the string (such as "1m").
The good thing is that kind of work lends itself well for unit testing.
You could probably obtain what you want by using directly a NumberFormat subclass but depending on how you're going to use it, the above design could be better.
static String[] prefixes = {"k","M","G"};
// Formats a double to a String with SI units
public static String format(double d) {
String result = String.valueOf(d);
// Get the prefix to use
int prefixIndex = (int) (Math.log10(d) / Math.log10(10)) / 3;
// We only have a limited number of prefixes
if (prefixIndex > prefixes.length)
prefixIndex = prefixes.length;
// Divide the input to the appropriate prefix and add the prefix character on the end
if (prefixIndex > 0)
result = String.valueOf(d / Math.pow(10,prefixIndex*3)) + prefixes[prefixIndex-1];
// Return result
return result;
}
// Parses a String formatted with SI units to a double
public static double parse(String s) {
// Retrieve the double part of the String (will throw an exception if not a double)
double result = Double.parseDouble(s.substring(0,s.length()-1));
// Retrieve the prefix index used
int prefixIndex = Arrays.asList(prefixes).indexOf(s.substring(s.length()-1)) + 1;
// Multiply the input to the appropriate prefix used
if (prefixIndex > 0)
result = result * Math.pow(10,prefixIndex*3);
return result;
}