Java - complex numbers - problem with imaginary unit - java

I'm having some issues with "i" in imaginary unit.
When I have "i" with number my program works. 4+4i it is ok.
But when I have only "i" does not want to work. 4+i doesn't work.
I have no idea how to change the code to solve this error. I know that below lines make this problem.
String x[] = str1.split("\\+|i|-");
String y[] = str2.split("\\+|i|-");
It is program for calculating multiplication(*), division(/), addition(+) and subtraction(-) of complex numbers typed as a string.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
private static DecimalFormat df = new DecimalFormat("0.0");
public static String Addition(double a_r, double a_i, double b_r, double b_i)
{
double x = a_r + b_r;
double y = a_i + b_i;
return df.format(x) + "+" + df.format(y) + "i";
}
public static String Subtraction(double a_r, double a_i, double b_r, double b_i)
{
double x = a_r - b_r;
double y = a_i - b_i;
return df.format(x) + "-" + df.format(y) + "i";
}
public static String Multiplication(double a_r, double a_i, double b_r, double b_i)
{
double x = a_r * b_r - a_i * b_i;
double y = a_r * b_i + a_i * b_r;
return df.format(x) + "+" + df.format(y) + "i";
}
public static String Division(double a_r, double a_i, double b_r, double b_i)
{
double x = a_r*b_r + a_i*b_i / b_r + b_i;
double y = a_r*b_i - a_i*b_r / b_r + b_i;
return df.format(x) + "+" + df.format(y) + "i";
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Num1");
String str1 = scan.nextLine();
System.out.println("Num2");
String str2 = scan.nextLine();
String x[] = str1.split("\\+|i|-");
String y[] = str2.split("\\+|i|-");
double a_real = Double.parseDouble(x[0]);
double a_img = Double.parseDouble(x[1]);
double b_real = Double.parseDouble(y[0]);
double b_img = Double.parseDouble(y[1]);
System.out.println(a_real);
System.out.println(a_img);
System.out.println(b_real);
System.out.println(b_img);
System.out.println(Addition(a_real, a_img, b_real, b_img));
System.out.println(Subtraction(a_real, a_img, b_real, b_img));
System.out.println(Multiplication(a_real, a_img, b_real, b_img));
System.out.println(Division(a_real, a_img, b_real, b_img));
}
}

Fix
You use the length of the array as condition
double a_img = x.length > 1 ? Double.parseDouble(x[1]) : 1;
double b_img = y.length > 1 ? Double.parseDouble(y[1]) : 1;
Improve
For now you code doesn't handle negative numbers, as the dash is in the split pattern. You may use a regex to match the parts you need : (-?\\d+)\\+?(-?\\d*)\\+?i
The parsing of the real part is easy, for the img you may check if the part is empty (case +i) and if the the part is just a dash (case -i)
Matcher m = Pattern.compile("(-?\\d+)\\+?(-?\\d*)\\+?i").matcher(value);
if (m.find()) {
System.out.println(m.group(1) + "<>" + m.group(2) + " ==>" + m.groupCount());
real = Double.parseDouble(m.group(1));
img = m.group(2).isEmpty() ? 1 : m.group(2).equals("-") ? -1 : Double.parseDouble(m.group(2));
} else {
throw new InvalidParameterException(value);
}
Object-Oriented programation
Designing a small class, the use could be like
class Complex {
private static final DecimalFormat df = new DecimalFormat("0.0");
private final double real, img;
public Complex(String value) {
Matcher m = Pattern.compile("(-?\\d+)\\+?(-?\\d*)\\+?i").matcher(value);
if (m.find()) {
System.out.println(m.group(1) + "<>" + m.group(2) + " ==>" + m.groupCount());
real = Double.parseDouble(m.group(1));
img = m.group(2).isEmpty() ? 1 : m.group(2).equals("-") ? -1 : Double.parseDouble(m.group(2));
} else {
throw new InvalidParameterException(value);
}
}
public Complex(double r, double i) {
real = r;
img = i;
}
public Complex add(Complex other) {
return new Complex(real + other.real, img + other.img);
}
public Complex substract(Complex other) {
return new Complex(real - other.real, img - other.img);
}
public Complex multiply(Complex other) {
return new Complex(real * other.real - img * other.img, real * other.img + img * other.real);
}
public Complex divide(Complex other) {
double denominator = Math.pow(other.real, 2) + Math.pow(other.img, 2);
return new Complex((real * other.real + img * other.img) / denominator,
(real * other.img - img * other.real) / denominator);
}
#Override
public String toString() { return df.format(real) + "+" + df.format(img) + "i";}
}
use
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input num1: ");
String str1 = scan.nextLine();
System.out.println("Input num2: ");
String str2 = scan.nextLine();
Complex c1 = new Complex(str1);
Complex c2 = new Complex(str2);
System.out.println(c1.add(c2));
System.out.println(c1.substract(c2));
System.out.println(c1.multiply(c2));
System.out.println(c1.divide(c2));
}

Related

Create a method that returns a String representation of random musical notes with random time duration for those notes?

I need the playGuitar method to return a string representation of 16 random notes of random duration. The output should look like: A(2), G(3), B(0.5), C(1), C(1), D(0.25), …].
Also, how do I get the Color data field to be displayed as blue or red and not RGB values in my Guitar Constructor?
I do not want to use arrays.
import java.awt.Color;
import java.util.Random;
public class Guitar {
private int numStrings = 6;
private double guitarLength = 28.2;
private String guitarManufacturer = "Gibson";
private Color guitarColor = Color.red;
Guitar(){
int numStrings = 6;
double guitarLength = 28.2;
String guitarManufacturer = "Gibson";
Color guitarColor = Color.red;
}
Guitar(int specStrings, double specLength, String specManufacturer, Color specColor){
numStrings = specStrings;
guitarLength = specLength;
guitarManufacturer = specManufacturer;
guitarColor = specColor;
//String s1 = Color.toString(specColor);
}
public String playGuitar(String str3){
Random rnd = new Random();
for (int iCount = 0; iCount<16 ; iCount++){
char a = (char) (rnd.nextInt(7) + 'A');
double b = (double) (rnd.nextInt(5)+1);
String str1 = Double.toString(b);
String str2 = Character.toString(a);
//System.out.println(a);
//System.out.println(str1);
str3 = str2+"("+str1+")";
continue;
//System.out.println(str2+"("+str1+")");
//System.out.println(str3);
//String str4 = String.toString(str3);
//System.out.println(str4);
}
return str3;
}
public String toString(){
return numStrings+" "+guitarLength+" "+guitarManufacturer+" "+guitarColor;
}
public int getNumStrings (){
return numStrings;
}
public double getGuitarLength(){
return guitarLength;
}
public String getGuitarManufacturer(){
return guitarManufacturer;
}
public Color getGuitarColor(){
return guitarColor;
}
}
I fixed the problems with your Guitar class and ran the following test of the playGuitar method. I manually formatted the output to fit in the answer.
F(2.75), G(2.50), G(0.75), A(0.25), D(1.75), G(0.75),
F(0.50), C(2.75), A(2.50), A(1.00), A(2.25), E(1.50),
D(2.50), G(1.25), A(0.50), G(1.00)
The major changes I made are;
I added a main method do I could test the Guitar class.
I fixed your empty constructor to use the instance variables.
I changed the guitar color to be a String since you wanted to display "red" or 'blue". The Color class is used to draw with actual colors using the Graphics or Graphics2D classes.
I fixed the multitude of problems with your playGuitar class.
Here's the code. I hope you learn something by reading the code.
import java.util.Random;
public class Guitar {
public static void main(String[] args) {
Guitar guitar = new Guitar();
System.out.println(guitar.playGuitar());
}
private int numStrings;
private double guitarLength;
private String guitarManufacturer;
private String guitarColor;
Guitar() {
numStrings = 6;
guitarLength = 28.2;
guitarManufacturer = "Gibson";
guitarColor = "red";
}
Guitar(int specStrings, double specLength,
String specManufacturer, String specColor) {
numStrings = specStrings;
guitarLength = specLength;
guitarManufacturer = specManufacturer;
guitarColor = specColor;
}
public String playGuitar() {
Random rnd = new Random();
String str3 = "";
for (int iCount = 0; iCount < 16; iCount++) {
char a = (char) (rnd.nextInt(7) + 'A');
double b = 0.25d * (rnd.nextInt(11) + 1);
String str1 = String.format("%.2f", b);
String str2 = Character.toString(a);
str3 += str2 + "(" + str1 + ")";
if (iCount < 15) {
str3 += ", ";
}
}
return str3;
}
#Override
public String toString() {
return numStrings + " " + guitarLength + " " +
guitarManufacturer + " " + guitarColor;
}
public int getNumStrings() {
return numStrings;
}
public double getGuitarLength() {
return guitarLength;
}
public String getGuitarManufacturer() {
return guitarManufacturer;
}
public String getGuitarColor() {
return guitarColor;
}
}

I keep getting an error when in call displayMapData in main method

How should I write the code to call "displayMapData" in main method. I would really appreciate the help.
Would be helpful if you provided the code so I can learn from my mistakes.
package stormtroopers;
import java.text.DecimalFormat;
public class StormTroopers
{
public static double eucldeanDistance(double x2, double x1, double 2, double y1)
{
double d = 0;
double xDif = Math.pow(x2-x1,2);
double yDif = Math.pow(y2-y1,2);
d = Math.sqrt(xDif + yDif);
return d;
}
public static String distanceBetweenLocations(double x, double y, double [][] locations)
{
String s = "\t";
double totalDistance = 0;
DecimalFormat df = new DecimalFormat("#.##");
for(int i=0; i < locations.length; i++)
{
double d = eucldeanDistance(x,locations[i][0],y,locations[i][1]);
totalDistance += d;
s = s + df.format(d) + "\t";
}
return s + df.format(totalDistance);
}
public static void displayMapData(double[][] locations,String author)
{
System.out.println("___________________STORMTROOPER DISTANCE DATA____________________");
System.out.println("\tST-1\t" + "\tST-2\t" + "\tST-1\t" + "\tST-4\t" + "\tST-5\t" + "\tST-6\t" + "\tST-7\t" + "\tST-8\t" + "\tST-9\t" + "\tST-10\t" + "TOTAL DISTANCE");
System.out.println();
for(int i = 0; i < locations.length; i++)
{
String s = distanceBetreenLocations(locations[i][0],locations[i][1],locations);
System.out.println("ST-" + (i + 1) + s);
System.out.println();
}
System.out.println("REPORT DATA CREATED BY " + author + "______________________");
}
public static void main(String[] args)
{
System.out.println(displayMapData(double[][] locations,String author);
}
}
Considering that your call in main to displayMapData() should be an actualy call, and isn't a method declaration, it should have data (a 2D array of doubles, and a String) instead of variable declarations.
Something like:
double[][] data = {{0.5, 5.8, 2.3},
{5.2, 3.4, 0.0},
{1.2, 1.6, 2.0}};
System.out.println(displayMapData(data, "Me");
Do it like this, it will work,
You might want to do spacing between answers and change your name
import java.text.DecimalFormat;
public class StormTrooper {
public static double euclideanDistance(double x2, double x1, double y2, double y1){
double d = 0;
double xDif = Math.pow(x2-x1,2);
double yDif = Math.pow(y2-y1,2);
d = Math.sqrt(xDif + yDif);
return d;
}
public static String distanceBetweenLocations (double x, double y, double[][] locations){
String s = "\t";
double totalDistance = 0;
DecimalFormat df = new DecimalFormat("#.##");
for (int i = 0; i < locations.length; i++){
double d = euclideanDistance(x,locations[i][0],y,locations[i][1]);
totalDistance += d;
s = s + df.format(d) + "\t";
}
return s + df.format (totalDistance);
}
public static void displayMapData(double[][] locations, String author){
System.out.println("________________________STORMTROOPER DISTANCE DATA_____________________________");
System.out.println("\tST-1\t" + "\tST-2\t" +"\tST-3\t" +"\tST-4\t" +"\tST-5\t" +"\tST-6\t"
+"\tST-7\t"
+ "\tST-8\t" +"\tST-9\t" +"\tST-10\t" + "TOTAL DISTANCE");
System.out.println();
for(int i = 0; i < locations.length; i++){
String s = distanceBetweenLocations(locations[i][0], locations[i][1], locations);
System.out.println("ST-" + (i + 1) + s);
System.out.println();
}
System.out.println("REPORN DATA CREATE BY" + author +
"_____________________________________________");
}
public static void main(String[] args){
double[][] inputs = { { 32, 16 }, { 32, 14 }, { 33, 13 }, {35, 13}, { 36, 13 }, { 37, 15 }, {36 ,16}, {35 ,16.5}, {34 ,15}, { 33,16 }};
String author = "Mayank";
displayMapData(inputs, author);
}
}

Launch various method with an other method

I want launch various method(exercise) with an other method with Scanner.
When the machine asks which exercises, I want to answer with a tapping answer and when I say the exercise(method), the machine launch this method with my tapping answer.
Exemple:
Which exercises?
me - "W34"
(The machine launches the method W34)
You have to use reflection.
Note: For more please write your code in question I will change it accordingly
obj.getClass().getMethod(methodName).invoke.invoke(obj);
Sorry i m not a professional, and sorry for the code it was my first question on this site, i only put in some exercises because there are so many.
Code :
public class Main {
public static String CapitalizeEachWord(String st) {
String result = "";
st = st.replaceAll("() ([A-Z])", "$1 $2");
String[] words = st.split(" ");
for (String word : words)
if (word.length() > 0)
result += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
return result;
}
public static String Scann() {
Scanner in = new Scanner(System.in);
System.out.println("Wich exercises? (W + exNumb)");
int x = in.nextInt();
return null;
}
public static String W1() {
System.out.println("Hello");
System.out.println("Antoine Sidot!");
System.out.println();
return null;
}
public static String W2() {
int result = 74 + 36;
System.out.println(result);
return null;
}
public static String W3() {
System.out.println(50/3);
return null;
}
public static String W4() {
System.out.println(-5 + 8 * 6);
System.out.println((55 + 9) % 9);
System.out.println(20 + -3*5 / 8);
System.out.println(5 + 15 / 3 * 2 -8 % 3);
return null;
}
public static String W5() {
int nb1 = 25;
int nb2 = 5;
System.out.println(nb1 + " x " + nb2 + " = " + nb1*nb2);
return null;
}
}

Search in Hashmap

Using for loop to compare the input value with the hashmap if it matches any value in the hash-map then the code prints all the related values with that time.
The result shows out for me NULL
System.out.println("Please enter time :");
Scanner scan = new Scanner(System.in);
String value = scan.nextLine();//Read input-time
Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
if(measurement != null){
System.out.println(measurement);
}}
Class Measurement:
public void getTimeInfo(String value)
{
value = Measurements.get(time);
if (value == null) {
throw new MeasurementException();
}
System.out.println("The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid );
}
}
}
Following the 3 steps (ignoring the Json part) u mentioned and reusing some of your code i can provide u this code:
Main.java:
public class Main {
static HashMap<String, Measurement> measurements = new HashMap();
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {//Create 3 measurements
String time = ""+i;
measurements.put(time, new Measurement(time, (float) i, (float) i, (float) i));
}
System.out.println("Please enter time :");
Scanner scan = new Scanner(System.in);
String value = scan.nextLine();//Read input-time
Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
if(measurement != null){
System.out.println(measurement);
}
}
}
Measurement.java:
public class Measurement {
String time ;
Float temp;
Float wind;
Float humid;
int iD;
public Measurement(String d, Float t, Float w, Float h){
this.time = d;
this.temp = t;
this.wind = w;
this.humid = h;
}
#Override
public String toString() {
return "The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid;
}
}
It might not fit exactly your needs but it can be a help.

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.

Categories