Complex Class, mutliply & divide not working - isml

I have first listed my class code, then my tester/driver code and have put my questions at the bottom. My code for my class is as follows :
class Complex {
//data values
private double real;
private double imag;
//constructors
public Complex () {
real = 0;
imag = 0;
}
public Complex (double realInput) {
real = realInput;
imag = 0;
}
public Complex (double realInput, double imagInput) {
real = realInput;
imag = imagInput;
}
//accessors
public double getReal () {
return real;
}
public double getImag () {
return imag;
}
//modifiers
public void setReal (double inputReal) {
real = inputReal;
}
public void setImag (double inputImag) {
imag = inputImag;
}
//toString method
public String toString() {
return real + " + " + imag + "i";
}
//instance methods
//addition methods
public Complex add (double realInput) {
real = real + realInput;
Complex newComplex = new Complex(real, imag);
return newComplex;
}
public Complex add (Complex complex) {
double firstReal = complex.getReal();
double firstImag = complex.getImag();
double secondReal = this.getReal();
double secondImag = this.getImag();
real = firstReal + secondReal;
imag = firstImag + secondImag;
Complex newComplex = new Complex(real, imag);
return newComplex;
}
//subtraction methods
public Complex subtract (double realInput) {
real = real - realInput;
Complex newComplex = new Complex(real, imag);
return newComplex;
}
public Complex subtract (Complex complex) {
double newReal = complex.getReal();
double newImag = complex.getImag();
real = this.getReal() - newReal;
imag = this.getImag() - newImag;
Complex newComplex = new Complex(real, imag);
return newComplex;
}
//multiplication methods
public Complex multiply (double realInput) {
real = real * realInput;
imag = imag * realInput;
Complex newComplex = new Complex(real, imag);
return newComplex;
}
//****problem code****
public Complex multiply (Complex complex) {
double newReal = complex.getReal();
double newImag = complex.getImag();
real = ((real * newReal) - (imag * newImag));
imag = ((real * newImag) + (imag * newReal));
Complex newComplex = new Complex(real, imag);
return newComplex;
}
//division methods
public Complex divide (double realInput) {
real = real / realInput;
imag = imag / realInput;
Complex newComplex = new Complex(real, imag);
return newComplex;
}
//****problem code****
public Complex divide (Complex complex) {
double newReal = complex.getReal();
double newImag = complex.getImag();
real = this.getReal();
imag = this.getImag();
double newRealNumerator = (real * newReal) + (imag * newImag);
double newRealDenominator = (Math.pow(newReal, 2) + Math.pow(newImag, 2));
real = newRealNumerator / newRealDenominator;
double newImagNumerator = (imag * newReal) - (real * newImag);
double newImagDenominator = newRealDenominator;
imag = newImagNumerator / newImagDenominator;
Complex newComplex = new Complex(real, imag);
return newComplex;
}
//equals method
public boolean equals (Complex complex) {
double firstReal = complex.getReal();
double firstImag = complex.getImag();
double secondReal = this.getReal();
double secondImag = this.getImag();
boolean testEquals = false;
if (firstReal == secondReal && firstImag == secondImag) {
testEquals = true;
}
return testEquals;
}
}//end class
My code for my tester/driver is as follows:
class ComplexTester {
public static void main(String[] args ) {
//declaring Complex objects
Complex one = new Complex ();
Complex two = new Complex (3);
Complex three = new Complex (1, 4);
Complex four = new Complex (2, 3);
//testing addition methods
System.out.println("Testing addition methods...");
System.out.println("(" + three.toString() + ") + (" + 3.0 + ") = " + three.add(3.0));
three.setReal(1);
three.setImag(4);
System.out.println("(" + three.toString() + ") + (" + four.toString() + ") = " + three.add(four));
three.setReal(1);
three.setImag(4);
//testing subtraction methods
System.out.println();
System.out.println("Testing subtraction methods...");
System.out.println("(" + three.toString() + ") - (" + 3.0 + ") = " + three.subtract(3.0));
three.setReal(1);
three.setImag(4);
System.out.println("(" + three.toString() + ") - (" + four.toString() + ") = " + three.subtract(four));
three.setReal(1);
three.setImag(4);
//testing multiplication methods
System.out.println();
System.out.println("Testing multiplication methods...");
System.out.println("(" + three.toString() + ") * (" + 3.0 + ") = " + three.multiply(3.0));
three.setReal(1);
three.setImag(4);
System.out.println("(" + three.toString() + ") * (" + four.toString() + ") = " + three.multiply(four));
three.setReal(6);
three.setImag(3);
//testing division method
System.out.println();
System.out.println("Testing division methods...");
System.out.println("(" + three.toString() + ") / (" + 3.0 + ") = " + three.divide(3.0));
three.setReal(4);
three.setImag(2);
Complex testDiv = new Complex(3, -1);
System.out.println("(" + three.toString() + ") / (" + testDiv.toString() + ") = " + three.divide(testDiv));
three.setReal(1);
three.setImag(4);
//testing equals method
System.out.println();
System.out.println("Testing equals method...");
if (three.equals(four) == true) {
System.out.println(three.toString() + " is equal to " + four.toString());
}
else {
System.out.println(three.toString() + " is not equal to " + four.toString());
}
Complex testEquals = new Complex(2, 3);
if (four.equals(testEquals) == true) {
System.out.println(four.toString() + " is equal to " + testEquals.toString());
}
else {
System.out.println(four.toString() + " is not equal to " + testEquals.toString());
}
}// end main method
}// end class
My first problem is that if I would call my add method on the three object [such as three.add(four) ] it completely changes the three object to the answer of three.add(four). What I did to get around that (and I'm assuming it's bad programming) is call the set methods to assign the three object back to what I needed.
My second problem is that the multiply and divide methods (that I have commented above with "****problem code****") are not reporting the correct complex number. The multiply problem code should show (-10.0 + 11.0i) in the tester but instead it shows (-10.0 + -22.0i) upon running. The divide problem code should show (1.0 + 1.0i) but instead it shows (1.0 + 0.7i) upon running.
To multiply a complex number by another complex number the formula is: (A + Bi) times (C + Di) = (AC - BD) + (AD + BC)i
To divide a complex number by another complex number the formula is: (A + Bi) divided by (C + Di) = (AC+BD)/(C2 + D2) + (BC-AD)/(C2 + D2)i
My key to convert from the letters of the formulas listed (A, B, C, D) and my own self-named variables is: A = real, B = imag, C = newReal, and D = newImag

real = ((real * newReal) - (imag * newImag));
imag = ((real * newImag) + (imag * newReal));
This updates your instance variable real and you are using this updated real variable in the calculation of imaginary part of the complex variable which is obviously wrong.
Your code should be like this.
public Complex multiply (Complex complex) {
double newReal = complex.getReal();
double newImag = complex.getImag();
double real = ((this.real * newReal) - (this.imag * newImag));
double imag = ((this.real * newImag) + (this.imag * newReal));
Complex newComplex = new Complex(real, imag);
return newComplex;
}

Related

methods classes and objects

I don't know what my error is I am not understanding classes
I have read a java book but its not helpful
classes codes and methods confuse me and though you figuring out my code i will have a better understanding of what those things actually do
public double intoxicated(double weight)
{
double numDrinks;
numDrinks = (0.08 + 0.015) * weight /
(12 * 7.5 * alcohol);
return numDrinks;
}
public class Beer
{
private String name;
private double alcohol;
public String getName(){
return name;
}
public void setName(String n)
{
this.name= name;
}
public double getAlcohol()
{
return Alcohol;
}
public void setAlcohol(double a)
{
this.age = age;
}
public double intoxicated(double weight)
{
double numDrinks;
numDrinks = (0.08 + 0.015) * weight /
(12 * 7.5 * alcohol);
return numDrinks;
}
public static void main(String[] args)
{
Beer beer1 = new Beer();
Beer beer2 = new Beer();
beer1.setName("Cors Light");
beer1.setAlcohol(0.042);
beer2.setName("Heinaken");
beer2.setAlcohol(0.042);
double lightWeight = 100.0;
double heavyWeight = 250.0;
double lightDrinks1 = beer1.intoxicated(lightWeight);
System.out.println("The number of " + beer1.getName() +
" drinks needed to make\na person weighing " +
lightWeight + " pounds intoxicated is " + lightDrinks1);
System.out.println();
double heavyDrinks1 = beer1.intoxicated(heavyWeight);
System.out.println("The number of " + beer1.getName() +
" drinks needed to make\na person weighing " +
heavyWeight + " pounds intoxicated is " + heavyDrinks1);
System.out.println();
double lightDrinks2 = beer2.intoxicated(lightWeight);
System.out.println("The number of " + beer2.getName() +
" drinks needed to make\na person weighing " +
lightWeight + " pounds intoxicated is " + lightDrinks2);
System.out.println();
double heavyDrinks2 = beer2.intoxicated(heavyWeight);
System.out.println("The number of " + beer2.getName() +
" drinks needed to make\na person weighing " +
heavyWeight + " pounds intoxicated is " + heavyDrinks2);
System.out.println();
Beer beer3 = new Beer();
beer3.setName("Miller Genuine Draft Light");
beer3.setAlcohol(0.042); // 4.2% alcohol
lightWeight = 100.0;
heavyWeight = 250.0;
double lightDrinks3 = beer3.intoxicated(lightWeight);
System.out.println("The number of " + beer3.getName() +
" drinks needed to make\na person weighing " +
lightWeight + " pounds intoxicated is " + lightDrinks3);
System.out.println();
double heavyDrinks3 = beer3.intoxicated(heavyWeight);
System.out.println("The number of " + beer3.getName() +
" drinks needed to make\na person weighing " +
heavyWeight + " pounds intoxicated is " + heavyDrinks3);
System.out.println();
}
}

While/if Loop is not working in class

I'm learning java and I'm having an issue with my if code not running.
In the following code I'm trying to determine if a number (variable num) is a triangle number (1,3, 6, 10 etc). The code should run through and give the "Is Triangle". However it keeps spitting out Null.
I understand this is not the most effective way to do this code, but I am trying to learn how to use Classes.
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 45;
int tri = 0;
int triplus = 0;
String triresult;
public String triangle() {
while (tri < num) {
if (tri == num) {
triresult = "Is a Triangle";
System.out.println("Is a Triangle");
} else if (tri + (triplus + 1) > num){
triresult = "Is Not a Triangle";
} else {
triplus++;
tri = tri + triplus;
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Thanks for any help provided.
Try this code :
public class HelloWorld {
public static void main(String[] args) {
class NumberShape {
int num = 10;//Try other numbers
int tri = 0;
int triplus = 0;
int res = 0;
String triresult = "Is Not a Triangle";
int[] tab= new int[num];
public String triangle() {
//to calculate the triangle numbers
for(int i = 0; i<num; i++){
res = res + i;
tab[i]=res;
}
//To check if num is a triangle or not
for(int i = 0; i<tab.length; i++){
System.out.println(">> " + i + " : " + tab[i]);
if(tab[i]== num){
triresult = num + " Is a Triangle";
break;//Quit if the condition is checked
}else{
triresult = num + " Is Not a Triangle";
}
}
return triresult;
}
}
NumberShape result = new NumberShape();
System.out.println(result.triangle());
}
}
Hope this Helps.
Step through the loop carefully. You'll probably see that there is a case where
(tri < num)
fails, and thus you fall out of the loop, while
(tri == num)
and
(tri + (triplus + 1) > num)
both fail too, so no text gets set before you fall out.
You probably want to do your if-tests within the method on just tri, not a modification of tri, so as to reduce your own confusion about how the code is working.

Overloading Operator Rational Error

So I have looked around because this seems to be a common homework problem for most C++ students, but I can't seem to find one that will answer my issue. I feel that I have filled out the code correctly but I get the same error each time.
Here is my code:
#include <iostream>
using namespace std;
class Rational
{
public:
Rational() {
num = 0;
denom = 1;
};
Rational(int n, int d) {
num = n;
denom = d;
normalize();
}
Rational(int n) {
num = n;
denom = 1;
}
int get_numerator() const {
return num;
}
int get_denominator() const {
return denom;
}
void normalize() {
if ((num > 0 && denom < 0)||(num < 0 && denom < 0)) {
num = -1 * num;
denom = -1 * denom;
}
int gcdcheck = GCD(num,denom);
num = num / gcdcheck;
denom = denom / gcdcheck;
}
int Rational::GCD(int n, int d) {
int temp;
n = abs(n);
d = abs(d);
if (n > d) {
// Do nothing everything is where it should be
}
else {
temp = n;
n = d;
d = temp;
}
int factor = n % d;
while (factor != 0) {
factor = n % d;
d = n;
n = factor;
}
return d;//Return the value to normalize to simplify the fractions to simplist form
}
Rational operator+(Rational b) const {
Rational add;
//Addition of fractions (a*d/b*d + c*b/d*b)
//Numerator = (a*d + c*b)
add.get_numerator = b.get_numerator * denom + b.get_denominator * num;
//Denomenator = (b*d)
add.get_denominator = b.get_denominator * denom;
add.normalize();
return add;
}
Rational operator-(Rational b) const {
Rational sub;
//Same as Addition just a minus sign
//Numerator = (a*d + c*b)
sub.get_numerator = b.get_numerator * denom + b.get_denominator * num;
//Denomenator = (b*d)
sub.get_denominator = b.get_denominator * denom;
sub.normalize();
return sub;
}
Rational operator*(Rational b) const {
//Multiply the numerators and denomenators
Rational multi;
multi.get_numerator = b.get_numerator * num;
multi.get_denominator = b.get_denominator * denom;
multi.normalize();
return multi;
}
Rational operator/(Rational b) const {
//Division of fractions is done by the recipricol of one of the fractions
Rational divi;
divi.get_numerator = b.get_numerator * denom;
divi.get_denominator = b.get_denominator * num;
divi.normalize();
return divi;
}
//To avoid issues with rounding the compare functions will multiply instead to give clean whole numbers
//This will be done by multiplying the denomenators by the opposite numerator
bool operator==(Rational b) const {
return ((b.get_numerator * denom == b.get_denominator * num));
}
bool operator<(Rational b) const {
return ((b.get_numerator * denom > b.get_denominator * num));
}
double toDecimal() const {
double result;
result = static_cast<double> (num)/ static_cast<double> (denom);
return result;
}
private:
int num = 0; // default value is 0
int denom = 1; // default value is 1
};
ostream& operator<<(std::ostream& output, Rational& a) {
if (a.get_denominator == 0) {
output << "Divide by Zero";
}
output << a.get_numerator << '/' << a.get_denominator;
return output;
}
I know its a lot of code and I don't expect someone to go through it all debugging I just thought I would post it all just in case the problem spans farther then where I think the issue is.
I get the same errors for each operator:
1: error C3867: 'Rational::get_denominator': non-standard syntax; use '&' to create a pointer to member
2: '*': error C3867: 'Rational::get_denominator': non-standard syntax; use '&' to create a pointer to member
3: error C3867: 'Rational::get_numerator': non-standard syntax; use '&' to create a pointer to member
I have looked at code from different online sites that have done this problem and tried their methods but it doesn't seem to work. I have added const and & to the parameters in the functions and I still get the same issues. Am I calling a function incorrectly or initializing one wrong?
You have multiple problems in the code. Here is the corrected code.
you were returning a value not a reference.
when you are defining a function inside the class you dont need to specify the full name
the () for function calls were missing
There are some comments on the code at the end.
#include <iostream>
#include <cmath>
using namespace std;
class Rational
{
public:
Rational()
{
num = 0;
denom = 1;
};
Rational(int n, int d)
{`
num = n;
denom = d;
normalize();
}
Rational(int n)
{
num = n;
denom = 1;
}
int& get_numerator()
{
return num;
}
int& get_denominator()
{
return denom;
}
void normalize()
{
if ((num > 0 && denom < 0) || (num < 0 && denom < 0))
{
num = -1 * num;
denom = -1 * denom;
}
int gcdcheck = GCD(num, denom);
num = num / gcdcheck;
denom = denom / gcdcheck;
}
int GCD(int n, int d)
{
int temp;
n = abs(n);
d = abs(d);
if (n > d)
{
// Do nothing everything is where it should be
}
else
{
temp = n;
n = d;
d = temp;
}
int factor = n % d;
while (factor != 0)
{
factor = n % d;
d = n;
n = factor;
}
return d;//Return the value to normalize to simplify the fractions to simplist form
}
Rational operator+(Rational b) const
{
Rational add;
//Addition of fractions (a*d/b*d + c*b/d*b)
//Numerator = (a*d + c*b)
add.get_numerator()= b.get_numerator() * denom + b.get_denominator() * num;
//Denomenator = (b*d)
add.get_denominator() = b.get_denominator() * denom;
add.normalize();
return add;
}
Rational operator-(Rational b) const
{
Rational sub;
//Same as Addition just a minus sign
//Numerator = (a*d + c*b)
sub.get_numerator() = b.get_numerator() * denom + b.get_denominator() * num;
//Denomenator = (b*d)
sub.get_denominator() = b.get_denominator() * denom;
sub.normalize();
return sub;
}
Rational operator*(Rational b) const
{
//Multiply the numerators and denomenators
Rational multi;
multi.get_numerator() = b.get_numerator() * num;
multi.get_denominator() = b.get_denominator() * denom;
multi.normalize();
return multi;
}
Rational operator/(Rational b) const
{
//Division of fractions is done by the recipricol of one of the fractions
Rational divi;
divi.get_numerator() = b.get_numerator() * denom;
divi.get_denominator() = b.get_denominator() * num;
divi.normalize();
return divi;
}
//To avoid issues with rounding the compare functions will multiply instead to give clean whole numbers
//This will be done by multiplying the denomenators by the opposite numerator
bool operator==(Rational b) const
{
return ((b.get_numerator() * denom == b.get_denominator() * num));
}
bool operator<(Rational b) const
{
return ((b.get_numerator() * denom > b.get_denominator() * num));
}
double toDecimal() const
{
double result;
result = static_cast<double> (num) / static_cast<double> (denom);
return result;
}
private:
int num = 0; // default value is 0
int denom = 1; // default value is 1
};
ostream& operator<<(std::ostream& output, Rational& a)
{
if (a.get_denominator() == 0)
{
output << "Divide by Zero";
}
output << a.get_numerator() << '/' << a.get_denominator();
return output;
}
Some comments on the code... Returning a reference, especially to a private member is really bad. I suggest you to create a set function.
so basically keep the get function as before
int get_denominator() const
{
return denom;
}
and create a new function to set value
int set_denominator(int in)
{
denom = in;
}
You try to call the function without the parethesis. It should be get_denominator()
Without the parenthesis you get the pointer to the function instead and try to perform an arythmetic on it - hence the error.

Netbeans Java illegal public static void with compiling?

The below throws an error for in public static void DemoMethod(). Why?
package demoblock;
/**
*
* #author coleen
*/
public class DemoBlock {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Demontrating block scope");
int x = 1111;
System.out.print("in first block x is" + x);
{
int y = 2222;
System.out.println(" In second block x is " + x);
System.out.println(" In seond block y is " + y);
}
{
int y = 3333;
System.out.println(" In third block x is " + x);
System.out.println(" In third block y is " + y);
DemoMethod();
System.out.println(" After method x is " + x);
System.out.println(" After method block y is " + y);
System.out.println(" At the end x is " + x);
public static void DemoMethod()
{
int x = 8888;
int y = 9999;
System.out.println(" In demoMethod x is " + x);
System.out.println(" In DemoMethod block y is " + y);
}
}
/** * * #author coleen */
public class DemoBlock
{
/**
* #param args
* the command line arguments
*/
public static void main( String[] args )
{
System.out.println( "Demontrating block scope" );
int x = 1111;
System.out.print( "in first block x is" + x );
{
int y = 2222;
System.out.println( " In second block x is " + x );
System.out.println( " In seond block y is " + y );
}
{
int y = 3333;
System.out.println( " In third block x is " + x );
System.out.println( " In third block y is " + y );
DemoMethod();
System.out.println( " After method x is " + x );
System.out.println( " After method block y is " + y );
System.out.println( " At the end x is " + x );
}
}
public static void DemoMethod()
{
int x = 8888;
int y = 9999;
System.out.println( " In demoMethod x is " + x );
System.out.println( " In DemoMethod block y is " + y );
}
}

User input with linear and binary searching in java

I'm trying to write a program that asks the user to input the size of the array the user wants to create, and then asks the user to fill the array with elements, and then it should display the array with its elements and, ask the user to conduct a search for an integer. It should conduct a linear and binary search, while displaying how many probes it took to determine is the element is in the array. So far the only output i have gotten is that the element has not been found. If you could look at my code and see what the problem is, because i have tried for hours and i have changed everything i can think of. Any help would be greatly appreciated.
import java.util.Scanner;
public class Searching
{
public static int[] anArray = new int[100];
private int numberOfElements;
public int arraySize = numberOfElements;
public String linearSearch(int value)
{
int count = 0;
boolean valueInArray = false;
String indexOfValue = "";
System.out.print("The Value was Found in: ");
for(int i = 0; i < arraySize; i++)
{
if(anArray[i] == value)
{
valueInArray = true;
System.out.print(i + " ");
indexOfValue += i + " ";
}
count ++;
}
if(!valueInArray)
{
indexOfValue = " None found";
System.out.print(indexOfValue);
}
System.out.println("\nIt took " + count + " probes with a linear search to find");
return indexOfValue;
}
public void binarySearch(int value)
{
int min = 0;
int max = arraySize - 1;
int count = 0;
while(min <= max)
{
int mid = (max + min) / 2;
if(anArray[mid] < value) min = mid + 1;
else if(anArray[mid] > value) max = mid - 1;
else
{
System.out.println("\nFound a Match for " + value + " at Index " + mid);
min = max + 1;
}
count ++;
}
System.out.println("It took " + count + " probes with a binary search to find");
}
public static void main(String[] args)
{
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("Input the number of elements in your Array");
int numberOfElements = scan.nextInt();
if(numberOfElements <= 0)
{
System.exit(0);
}
int[] anArray = new int[numberOfElements];
System.out.println("\nEnter " + numberOfElements + " Integers");
for(int i = 0; i < anArray.length; i ++)
{
System.out.println("Int # " + (i + 1) + ": ");
anArray[i] = scan.nextInt();
}
System.out.println("\nThe integers you entered are: ");
for(int i = 0; i < anArray.length; i ++) // for loop used to print out each element on a different line
{
System.out.println(anArray[i]);
}
System.out.println("Which element would you like to find?");
int value = scan.nextInt();
Wee3Q2JOSHBALBOA newArray = new Wee3Q2JOSHBALBOA();
newArray.linearSearch(3);
newArray.binarySearch(value);
}
}
hmm I am not sure you are using an array the correct way, you see an Array is a set size and I dont think you can expand like they way you are doing...
Instead try setting the size of the array to certain length.
Or use vectors