Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Apr 7th, 2008, 9:10 PM   #1
reddyfire
Newbie
 
Join Date: Apr 2008
Posts: 2
Rep Power: 0 reddyfire is on a distinguished road
Complex Number Calculator

So I'm trying to create a program to calculate complex numbers. The program contains two parts of code the Complex.java which contains the formulas for calculating the math and the calculator.java that asks for the input and computes everything. My program runs the way it is supposed to except for the fact that it doesn't register negative numbers when they are entered. Here is my code.
import java.util.StringTokenizer;

public class Complex
{ 
	private double real, imaginary;
	
	public Complex()
	{
		real=0;
		imaginary=0;
	}
	
	public Complex(double r, double i)
	{
		real = r;
		imaginary = i;
	}
		
	public String toString()
	{
		String R = "";
		String I = "";
		String r = Double.toString(real);
		String i = Double.toString(imaginary);
		int pointR = r.indexOf(".");
		int pointI = i.indexOf(".");
		int lengthR = r.length();
		int lengthI = i.length();
		
		
		// check if values are whole and cut off the ".0" part
		if (r.charAt(lengthR-1)=='0')
		{
			for (int k = 0; k < pointR; k++)
			{
				R = R + r.charAt(k);
			}
		}
		if (i.charAt(lengthI-1)=='0')
		{
			for (int k = 0; k < pointI; k++)
			{
				if (i.charAt(k) == '-')
				I = I + i.charAt(k) + " ";
				else
				I = I + i.charAt(k);
			}
		}	
		// all IFs are executed if the values are NOT whole
		// when REAL is 0 and IMAGINARY is POSITIVE
		if (R.equals("0") && imaginary > 0 && R.equals("") && I.equals(""))
		{
			String s = ("(" + "i" + ")");
			return s;
		}
		// when REAL is 0 and IMAGINARY is NEGATIVE
		if (R.equals("0") && imaginary < 0 && R.equals("") && I.equals(""))
		{
			String s = ("(" + "-" + "i" + ")");
			return s;
		}
		// when REAL is 0 and IMAGINARY is 0
		if (R.equals("0") && imaginary == 0.0 && R.equals("") && I.equals(""))
		{
			String s = ("(0)");
			return s;
		}
		// when REAL is POSITIVE and IMAGINARY is NEGATIVE
		if (real > 0.0 && imaginary < 0.0 && R.equals("") && I.equals(""))
		{
			for (int k = 0; k < (lengthI-1); k++)
			{
				I = I + i.charAt(k);
				if (i.charAt(k) == '-')
				{
					I = I + " ";
				}
			}
			String s = ("("+ r + " " + I + "i" + ")");
			return s;
		}
		// when REAL is POSITVE and IMAGINARY is 0
		if (real > 0.0 && imaginary == 0.0 && R.equals("") && I.equals(""))
		{
			String s = ("(" + R + ")");
			return s;
		}
		// when REAL is NEGATIVE and IMAGINARY is 0
		if (real < 0.0 && imaginary == 0.0 && R.equals("") && I.equals(""))
		{
			String s = ("(" + R + ")");
			return s;
		}
		// when BOTH ARE NEGATIVE
		if (real < 0.0 && imaginary < 0.0 && R.equals("") && I.equals(""))
		{
			String s = ("(" + R + " " + I + "i" + ")");
			return s;
		}
		// when REAL is NEGATIVE and IMAGINARY is POSITIVE
		if (real < 0.0 && imaginary > 0.0 && R.equals("") && I.equals(""))
		{
			String s = ("(" + r + " + " + i + "i" + ")");
			return s;
		}
		// when BOTH are POSITIVE
		if (real > 0.0 && imaginary > 0.0 && R.equals("") && I.equals(""))
		{
			String s = ("(" + r + " + " + i + "i" + ")");
			return s;
		}
		// when values ARE WHOLE
		String s = ("(" + R + " + " + I + "i" + ")");
		return s;
	
	}

	public Complex add( Complex c)
	{ 
		return new Complex (real+c.real, imaginary+c.imaginary);
	}
	
	public Complex subtract(Complex c)
	{
		return new Complex (real-c.real, imaginary-c.imaginary);
	}
	
	public Complex multiply(Complex c)
	{
		Complex C = new Complex (real*c.real - imaginary*c.imaginary, real*c.imaginary + c.real*imaginary);	
		return C;
	}
	
	public Complex divide(Complex c)
	{
		double Real = (real*c.real+imaginary*c.imaginary)/(Math.pow(c.real, 2) + Math.pow(c.imaginary, 2));
		double Imaginary = (imaginary*c.real - real*c.imaginary)/(Math.pow(c.real, 2) + Math.pow(c.imaginary, 2));
		
		return new Complex(Real, Imaginary); 		
	}


}

import java.io.*;
import java.util.StringTokenizer;

public class Calculator
{
	public static void main(String[] args)
	{
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		Complex num1, num2, result = new Complex();
		char op;
		boolean more;
		System.out.println("\n Complex number calculation program \n");
		do
		{
			num1 = readComplex(in, "Enter the 1st number you would like: ");
			num2 = readComplex(in, "Enter the 2nd number you would like: ");
			op = readChar(in, "Enter the operation to be preformed '+, -, *, or /': ", "+-*/");
			switch (op)
			{
				case '+': result = num1.add(num2);
				break;
				case '*': result = num1.multiply(num2);
				break;
				case '/': result = num1.divide(num2);
				break;
				case '-': result = num1.subtract(num2); 
			}	
			System.out.println(num1+" "+op+" "+num2+" = "+result);
			more = (readChar(in, "Want to do another calculation? (y/n): ", "yn") !='n');
		}
		while (more);
		System.out.println("\n Calculations have been completed \n");
	}
// Method to read a complex number
	public static Complex readComplex(BufferedReader in, String s)
	{
		System.out.print(s);
		double real = 0;
		double img = 0;
		boolean doit = true;
		//begins loop for user input
		while (true)
		{
			try
			{
				//reads input from user and checks for "i" for correct format
				String inp = in.readLine();
				int qwer = inp.indexOf("i");
				if (inp.indexOf("i") == -1)
				{	
					throw new IOException();
				}
				//Tokenizes the sring by using delimters which ar +,-,_,tab, newline, i
				StringTokenizer t = new StringTokenizer(inp, "+- //t/n/ri");
				//checks to see if there are tokens and store the value in double "real" 
				if (t.hasMoreTokens())
				{
					real = Double.parseDouble(t.nextToken());
				}
				else throw new IOException();
				//check if there are tokens and store value in double "img"
				if (t.hasMoreTokens())
				{
					img = Double.parseDouble(t.nextToken());
				}
				else throw new IOException();
				//if the program has no problems then set vaule of doit to true
				doit = true;
			}
			//handles the NumberFormatException
			catch (NumberFormatException e)
			{
				System.out.print ("\n Incorrect format, try again (num + numi): ");
				doit = false;
			}
			//handles the IOException
			catch (IOException e)
			{
				System.out.print ("\n Incorrect format, try again (num + numi): ");
				doit = false;
			}	
			//If no problems then it creates a complex object with real and img variables. 
			if (doit == true)
			{
				Complex c = new Complex(real, img);
				return c;
			}
		}
		
	}
// Method reads the first character of a string
	public static char readChar(BufferedReader in, String prompt, String chars)
	{
		System.out.print (prompt);
		String inp = "";
		while (true)
		{
			try
			{
				inp = in.readLine();
			}
			catch (IOException e)
			{
				System.out.println ("\n There is an Error!");
			}
				if (chars.indexOf(inp.charAt(0)) >= 0 )
				return chars.charAt(chars.indexOf(inp.charAt(0)));
				else 
				System.out.print("\nIncorrect value (use: + - / *): ");
		}
	}	
}
An example of the error I am getting is lets say I take a set of complex numbers like this (-1+2i) + (-3+4i) it should return -4 + 6i but instead it is printing (1+2i) + (3 + 4i) = 4 + 6i. It completely ignores the negative numbers and puts them in as positive. If anyone could let me know what I am doing wrong I would greatly appreciate it. Thanks.
reddyfire is offline   Reply With Quote
Old Apr 7th, 2008, 11:19 PM   #2
Wizard1988
Professional Programmer
 
Wizard1988's Avatar
 
Join Date: Oct 2005
Location: Chitown
Posts: 416
Rep Power: 3 Wizard1988 is on a distinguished road
Send a message via AIM to Wizard1988
Re: Complex Number Calculator

It is most likely the way you handle the input. You could check the string for a negative sign and them simply subtract the following number from 0. Its just a simple hack, other members might have a better idea.
__________________
JG-Webdesign
Wizard1988 is offline   Reply With Quote
Old Apr 8th, 2008, 6:58 AM   #3
OpenLoop
Expert Programmer
 
OpenLoop's Avatar
 
Join Date: May 2005
Location: East Lansing, MI
Posts: 663
Rep Power: 4 OpenLoop is on a distinguished road
Re: Complex Number Calculator

java Syntax (Toggle Plain Text)
  1. StringTokenizer t = new StringTokenizer(inp, "+- //t/n/ri");
I think this is your problem. If I understand it correctly, this will return the numbers delimited by + or - or tab... So it will ignore the delimiter, and return the values between them causing you to lose the negative sign.
OpenLoop is offline   Reply With Quote
Old Apr 8th, 2008, 1:58 PM   #4
reddyfire
Newbie
 
Join Date: Apr 2008
Posts: 2
Rep Power: 0 reddyfire is on a distinguished road
Re: Complex Number Calculator

Quote:
Originally Posted by OpenLoop View Post
java Syntax (Toggle Plain Text)
  1. StringTokenizer t = new StringTokenizer(inp, "+- //t/n/ri");
I think this is your problem. If I understand it correctly, this will return the numbers delimited by + or - or tab... So it will ignore the delimiter, and return the values between them causing you to lose the negative sign.
Yes that fixed my problem thank you very much.
reddyfire is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Java Entering a Number or Letter kewlgeye Java 9 Apr 5th, 2008 3:55 PM
Guess a Number 3n! C++ 7 Dec 2nd, 2007 3:38 AM
c-unix-childprocesses-random number programmingnoob C 7 Feb 6th, 2007 8:39 PM
Python calculator problem Nebula Python 14 Feb 8th, 2006 12:24 PM
pointer number alteration Blighttdm C 5 Oct 14th, 2005 7:24 PM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 7:57 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC