everyone so I'm writting a program that solves quadratics (one doubled root and two doubled roots this seems to work but somehow I can't get it to solve complex roots? any help.
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
//} else if (disc < 0) {
//displayComplexConjugates();
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
//} else {
//System.out.println("Help! Arithmetic has failed!");
//
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
The solution:
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
} else {
// New method
displayComplexRoots(a,b,c);
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
// New method
public static void displayComplexRoots(double a, double b, double c) {
double disc = 4 * a * c - b * b;
double dobleA = 2 * a;
String s = "two roots (" + (-b/dobleA) + "+" + (Math.sqrt(disc)/dobleA) + "i) and ("+ (-b/dobleA) + "" + (-Math.sqrt(disc)/dobleA) + "i)";
JOptionPane.showMessageDialog(null, s);
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
General solution with complex numbers:
public class Complex {
double r;
double i = 0;
public Complex(double real, double imaginary) {
this.r = real;
this.i = imaginary;
}
public Complex(double real) {
this.r = real;
}
public Complex add(Complex c){
return new Complex(r+c.r, i+c.i);
}
public Complex cross(Complex c){
return new Complex(r*c.r - i*c.i, i*c.r + r*c.i);
}
public double getR() {
return r;
}
public double getI() {
return i;
}
#Override
public String toString() {
String result = Double.toString(r);
if (i < 0) {
result += " - " + ((i != -1)?Double.toString(-i):"") + "i";
} else if (i > 0) {
result += " + " + ((i != 1)?Double.toString(i):"") + "i";
}
return result;
}
public Complex[] squareRoot(){
double r2 = r * r;
double i2 = i * i;
double rR = Math.sqrt((r+Math.sqrt(r2+i2))/2);
double rI = Math.sqrt((-r+Math.sqrt(r2+i2))/2);
return new Complex[]{new Complex(rR, rI),new Complex(-rR, rI)};
}
public static Complex[] quadraticsRoot(double a, double b, double c) {
Complex[] result = new Complex(b*b - 4*a*c).squareRoot();
Complex bNegative = new Complex(-b);
Complex divisor = new Complex(1.0d / (2 * a));
for (int j = 0; j < result.length; j++) {
result[j] = bNegative.add(result[j]).cross(divisor);
}
return result;
}
public static void main(String[] args) {
Complex[] sol = quadraticsRoot(1,-10,34);
System.out.println(sol[0]);
System.out.println(sol[1]);
}
}
Related
I would like to send multiple values from my getMultiples method to my main method using a return statement and no print or println statements.
public class StaticMethods {
public static void main (String[] args) {
int a = 6;
int b = 9;
int result = getMultiple(a,b);
System.out.println(result + "\n")
System.out.println("The first " + a + " multiples of " + b + " are: ");
int p = getMultiples(a,b);
}
public static int getMultiple(int a,int b) {
return (int) (a * b);
}
public static int getMultiples(int a, int b) {
int p = 0;
for (int i = 1; i <= a; i++) {
p = getMultiple(a,i);
}
return (p);
}
}
I have tried putting the return statement in the for loop but it does not work.
In Java as soon as return is encountered in the code, method is removed from execution stack and flow is returned back to calling method. So you can not return multiple values from a method. Rather you should create a list/array and return that as below(array example):
public class StaticMethods {
public static void main (String[] args) {
int a = 6;
int b = 9;
int result = getMultiple(a,b);
System.out.println(result + "\n");
System.out.println("The first " + a + " multiples of " + b + " are: ");
int p[] = getMultiples(a,b);
}
public static int getMultiple(int a,int b) {
return (int) (a * b);
}
public static int[] getMultiples(int a, int b) {
int[] p = new int[a];
for (int i = 1; i <= a; i++) {
p[i-1] = getMultiple(a,i);
}
return p;
}
}
I want to create a class ComplexMatrix that has field a array[NxN] of type ComplexNumber. I already made a ComplexNumber class as you can see below:
public class ComplexNumber {
private double real;
private double img;
// Getters and setters
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImg() {
return img;
}
public void setImg(double img) {
this.img = img;
}
// Constructor
public ComplexNumber(double real, double img) {
this.real = real;
this.img = img;
}
// Add
public ComplexNumber addComp(ComplexNumber num) {
ComplexNumber num1 = new ComplexNumber(real + num.real, img + num.img);
return num1;
}
// Subtract
public ComplexNumber subtractComp(ComplexNumber num) {
ComplexNumber num1 = new ComplexNumber(real - num.real, img - num.img);
return num1;
}
// Multiply
public ComplexNumber multiplyComp(ComplexNumber num) {
ComplexNumber num1 = new ComplexNumber(real*num.real-img*num.img,real*num.img+img*num.real);
return num1;
}
// Is Equals
boolean equals(ComplexNumber num) {
ComplexNumber num1 = new ComplexNumber(real, img);
if (num.real == num1.real && num.img == num1.img) {
return true;
} else {
return false;
}
}
#Override
public String toString() {
if (img > 0) {
return getReal() + " + " + Math.abs(getImg()) + "i";
}
if (img < 0) {
return getReal() + " - " + Math.abs(getImg()) + "i";
}
if (real==0) {
return getImg() + "i";
}
if (img==0) {
return getReal() + "";
}
return null;
}
}
that has some methods and its own toString that prints as follows:
3.51 + 1.87i
2.35 - 5.61i
-8.45 + 2.65i
The implemented ComplexMatrix has an array [M][N] as a field, and the cronstructor public ComplexMatrix(int rows, int cols) gives the array
random numbers from one to ten using the method computeRandom. Then a
toString() functions (which also implemets toSting() from ComplexNumber class) , should print the random numbers array. A desired print of ComplexMatrix would be:
[1.24 + 2.55i, -0.32 + 2.00i, 1.35 - 5.88i;
-5.71 - 5.91i, 0.29 – 9.14i, 0.00 + 3.51i;
6.44 + 0.00i, -3.51 – 0.67i, 2.10 + 4.20i;]
Here is ComplexMatrix class:
import java.util.Random;
public class ComplexMatrix {
private ComplexNumber[][] complexArray;
// Default Constructor
public ComplexMatrix() {
super();
this.complexArray = null;
}
// Copy Constructor
public ComplexMatrix(ComplexMatrix original) {
super();
original.complexArray = complexArray;
}
private Random rand = new Random();
private double computeRandom() {
int randomNum = (int) ((rand.nextDouble() - 0.5) * rand.nextInt(20) * 100);
return randomNum / 100.0;
}
// Random Numbers Constructor
public ComplexMatrix(int rows, int cols) {
double real = 0;
double img = 0;
ComplexNumber[][] complexArray= new ComplexNumber[rows][cols];
for (int i = 0; i < rows; i++) {
System.out.print("\n");
for (int j = 0; j < cols; j++) {
real = computeRandom();
img = computeRandom();
complexArray[i][j] = new ComplexNumber(real, img);
//edw peiramatizomai..to print 8a ginetai sthn toString()
System.out.print(complexArray[i][j].toString());
System.out.print("\t");
}
}
}
#Override
public String toString() {
int rows = 0,cols = 0;
//ComplexNumber[][] complexArray= new ComplexNumber[rows][cols];
ComplexMatrix s = new ComplexMatrix(rows,cols);
String out = "[";
//????????????????????????????????????
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
//????????
out = s.toString();
}
out += "]";
return out;
}
}
I'm just going to give pseudo-code (partly on the assumption that this is an assignment). But hopefully this gives you enough to get going with an implementation without just plain giving the solution.
#Override
public String toString() {
out = "[";
for (row : rows) {
if (notFirstRow) {
out += "\n"; // New line
}
for (column : columns) {
if (notFirstColumn) {
out += ", ";
}
out += matrix[row][column].toString();
}
}
out += "]";
return out;
}
Warning, I make no claims that this is optimal, or that there aren't better ways to format a matrix (or complex numbers)... But if you can flesh this out to actually compile I suspect you'll have what you're after.
I think the main problem here is to print according to your desired format. Here is sample code to achieve this:
#Override
public String toString() {
StringBuilder out = new StringBuilder();
out = out.append("[");
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
out.append(String.valueOf(matrix[row][column]));
//Populate according to whether last column or not.
out.append(column != columns - 1 ? ", " : ";");
}
out.append(row != rows - 1 ? "\n" : "");
}
out.append("]");
return out.toString();
}
Just remember, for nested arrays you have an Arrays.deepToString method available in standard library.
I already posted this question but I gave it a try I'm not sure if I'm on the right track:
Make a util class with three methods. First method's name is add, that returns the result by adding two numbers.
Second method's name is multiply, that returns the result by multiplying two numbers.
Third's method name is division that returns a result by dividing first parameter by second parameter. How would I do this part?
This is what I've got so far:
public class Util {
public static int add(int a, int b) {
int result = a + b;
System.out.println("result = " + result);
return result;
}
public static void main(String[] args) {
int res = add(5, 2);
System.out.println("res = " + res);
}
public static int multiply(int a, int b) {
int result = a * b;
System.out.println("result = " + result);
return result;
}
public static void main(String[] args) {
int res = multiply(5, 2);
System.out.println("res = " + res);
}
}
I think what you are confusing is the multiple main methods. You should only have 1 entry point (main) in your code, the rest of your util class is correct.
public class Util {
public static int add(int a, int b){
int result = a + b;
System.out.println("result = " + result);
return result;
}
public static int multiply(int a, int b){
int result = a * b;
System.out.println("result = " + result);
return result;
}
public static int divide(int a, int b){
int result = a / b;
System.out.println("result = " + result);
return result;
}
public static void main(String[] args) {
int[] aValues = {1,2,3,4};
int[] bValyes = {4,3,2,1};
for (int i = 0; i < aValues.length; i++) {
int a = aValues[i];
int b = bBalues[i];
int res = multiply(a, b);
System.out.println("res = " + res);
res = add(a, b);
System.out.println("res = " + res);
res = divide(a, b);
System.out.println("res = " + res);
}
}
}
This program is on Eclipse. I have to declare variables "Integer" not "int". When I am compiling this code shows no error but there is a runtime error. Please fix this problem.
Runtime error:
Exception in thread "main" java.lang.NullPointerException
at Polynomial.add(Polynomial.java:17)
at PolynomialTest.main(PolynomialTest.java:7)
Polynomial.java
public class Polynomial{
Integer coef[];
Integer exp;
public Polynomial(Integer a, Integer b) {
coef = new Integer[b+1];
coef[b] = a;
exp = b;
}
// return c = a + b
public Polynomial add(Polynomial b) {
Polynomial a = this;
Polynomial c= new Polynomial(0, Math.max(a.exp, b.exp));
for (Integer i = 0; i <= a.exp; i++){
c.coef[i] = c.coef[i] + a.coef[i];
}
for (int i = 0; i <= b.exp; i++){
c.coef[i] += b.coef[i];
}
return c;
}
public String toString() {
if (exp == 0){
return "" + coef[0];
}else
if (exp == 1){
return coef[1] + "x + " + coef[0];
}
String s = coef[exp] + "x^" + exp;
for (int i = exp-1; i >= 0; i--) {
if (coef[i] == 0){
continue;
}
else if (coef[i] > 0){
s = s + " + " + ( coef[i]);
}
if (i == 1){
s = s + "x";
}
else
if (i > 1) {
s = s + "x^" + i;
}
}
return s;
}}
PolynomialTest.java
public class PolynomialTest {
// test client
public static void main(String[] args) {
Polynomial p1 = new Polynomial(4, 4);
Polynomial p2 = new Polynomial(7, 2);
Polynomial p3 = new Polynomial(3, 0);
Polynomial p = p1.add(p2).add(p3); // 4x^3 + 3x^2 + 1
Polynomial q1 = new Polynomial(2, 2);
Polynomial q2 = new Polynomial(5, 4);
Polynomial q = q1.add(q2);
System.out.println("p(x) = " + p);
System.out.println("q(x) = " + q);
System.out.println("p(x) + q(x) = " + p.add(q));
}
}
Since Integer is an Object, you will need to initialize each entry in your coef array with a new Integer object.
You could just do this in the Polynomial constructor:
public class Polynomial{
Integer coef[];
Integer exp;
public Polynomial(Integer a, Integer b) {
coef = new Integer[b+1];
for (int i = 0; i < coef.length; i++){
coef[i] = new Integer(0); //create a new Integer and initialize to zero
}
coef[b] = a;
exp = b;
}
Can anybody help me with this?
simple pizza order program
I tried to run it in commandpromt and there are a lot of error
I have tried to change the double into int.. but the result is still error
<pre>
public class PizzaOrder
{
public static final String PIZZA_SMALL = "S";
public static final String PIZZA_MEDIUM = "M";
public static final String PIZZA_LARGE = "L";
public static final String PIZZA_COLLOSAL = "C";
public static final double SMALL_DIAMETER = 9;
public static final double MEIDUM_DIAMETER = 13;
public static final double LARGE_DIAMETER = 17;
public static final double COLOSSAL_DIAMETER = 26;
public static final double PRICE_SMALL = 8;
public static final double PRICE_MEDIUM = 11;
public static final double PRICE_LARGE = 15;
public static final double PRICE_COLOSSAL = 21;
public static final double PRICE_TAX = 0.095;
public static final double PRICE_TOPPING = 0.99;
public static final int MAX_TOPPINGS = 8;
public static final int MIN_TOPPINGS = 0;
/**
* Pizza Order
*
* #param args command-line arguments
*/
public static int getDiameter(String pizzaName)
{
if (pizzaName.equals(PIZZA_SMALL))
{
return SMALL_DIAMETER;
}
else if (pizzaName.equals(PIZZA_MEIDUM))
{
return MEDIUM_DIAMETER;
}`enter code here`
else if (pizzaName.equals(PIZZA_LARGE))
{
return LARGE_DIAMETER;
}
else
{
return COLOSSAL_DIAMETER;
}
}
public static int getBasePrice(String pizzaName)
{
if (pizzaName.equals(PIZZA_SMALL))
{
return PRICE_SMALL;
}
else if (pizzaName.equals(PIZZA_MEIDUM))
{
return PRICE_MEDIUM;
}
else if (pizzaName.equals(PIZZA_LARGE))
{
return PRICE_LARGE;
}
else
{
return PRICE_COLOSSAL;
}
}
there are error about the scanner too idk why
there are 13-20 errors and mostly because of the variables PIZZA_SMALL, etc
some errors say "incompetible types" and the other says "cannot find symbol"
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you"
+ "want: (S/M/L/C)");
String option = keyboard.nextLine().trim().substring(0,
1).toUppercase();
double pizzaPrice;
double pizzaSize;
if(option.equals(PIZZA_SMALL))
{
pizzaPrice = SMALL_DIAMETER;
pizzaSize = SMALL_DIAMETER;
}
else if (option.equals(PIZZA_MEIDUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else
{
option = PIZZA_COLOSSAL;
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping = keyboard.nextInt();
if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
else
{
pizzaTopping = pizzaTopping;
}
int radius = getDiameter(option) / 2;
double squareInches = radius * radius * Math.PI;
System.out.println("Pizza Size: " + option + "( " + pizzaSize +
"inch -- " + squareInches + " square inches)" );
System.out.println("Toppings: " + pizzaTopping);
double priceWithToppings = getBasePrice(option) + pizzaTopping * 9;
System.out.println("Price: " + priceWithToppings);
double pizzaTax = priceWithToppings * PRICE_TAX;
System.out.println("Tax: "+ pizzaTax);
double totalPrice = priceWithToppings + pizzaTax;
System.out.println("Total Price: " + totalPrice);
double priceEachSquareInch = priceWithToppings / squareInches;
System.out.println("Price/sq.in.: " + priceEachSquareInch);
}
}
Your PizzaOrder class should be as follows:
public class PizzaOrder {
public static final String PIZZA_SMALL = "S";
public static final String PIZZA_MEDIUM = "M";
public static final String PIZZA_LARGE = "L";
public static final String PIZZA_COLLOSAL = "C";
public static final double SMALL_DIAMETER = 9;
public static final double MEDIUM_DIAMETER = 13;
public static final double LARGE_DIAMETER = 17;
public static final double COLOSSAL_DIAMETER = 26;
public static final double PRICE_SMALL = 8;
public static final double PRICE_MEDIUM = 11;
public static final double PRICE_LARGE = 15;
public static final double PRICE_COLOSSAL = 21;
public static final double PRICE_TAX = 0.095;
public static final double PRICE_TOPPING = 0.99;
public static final int MAX_TOPPINGS = 8;
public static final int MIN_TOPPINGS = 0;
/**
* Pizza Order
*
* #param args
* command-line arguments
*/
public static double getDiameter(String pizzaName) {
if (pizzaName.equals(PIZZA_SMALL)) {
return SMALL_DIAMETER;
} else if (pizzaName.equals(PIZZA_MEDIUM)) {
return MEDIUM_DIAMETER;
} else if (pizzaName.equals(PIZZA_LARGE)) {
return LARGE_DIAMETER;
} else {
return COLOSSAL_DIAMETER;
}
}
public static double getBasePrice(String pizzaName) {
if (pizzaName.equals(PIZZA_SMALL)) {
return PRICE_SMALL;
} else if (pizzaName.equals(PIZZA_MEDIUM)) {
return PRICE_MEDIUM;
} else if (pizzaName.equals(PIZZA_LARGE)) {
return PRICE_LARGE;
} else {
return PRICE_COLOSSAL;
}
}
}
Notice how I corrected the return type from int to double on getDiameter and getBasePrice, as the constants you are trying to return are double. I also fixed the misspelling of "Medium" in some places.
To fix the scanner error, you must import it's package using: (Add this at the top of the file)
import java.util.Scanner;
You main method should look like this: (Again, misspelling variables and casting errors)
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you" + "want: (S/M/L/C)");
String option = keyboard.nextLine().trim().substring(0,1).toUpperCase();
double pizzaPrice;
double pizzaSize;
if(option.equals(PIZZA_SMALL))
{
pizzaPrice = SMALL_DIAMETER;
pizzaSize = SMALL_DIAMETER;
}
else if (option.equals(PIZZA_MEDIUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else
{
option = PIZZA_COLLOSAL;
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping = keyboard.nextInt();
if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
double radius = getDiameter(option) / 2;
double squareInches = radius * radius * Math.PI;
System.out.println("Pizza Size: " + option + "( " + pizzaSize +
"inch -- " + squareInches + " square inches)" );
System.out.println("Toppings: " + pizzaTopping);
double priceWithToppings = getBasePrice(option) + pizzaTopping * 9;
System.out.println("Price: " + priceWithToppings);
double pizzaTax = priceWithToppings * PRICE_TAX;
System.out.println("Tax: "+ pizzaTax);
double totalPrice = priceWithToppings + pizzaTax;
System.out.println("Total Price: " + totalPrice);
double priceEachSquareInch = priceWithToppings / squareInches;
System.out.println("Price/sq.in.: " + priceEachSquareInch);
}
}
If you want to cast a double to an int, you need to do int something = (int)myDouble. Also pay attention when writing your variable names, as they must be exactly the same as the definition or they will throw an error. Also, if a method returns an int, but you try and return a double, it will result in an error, as the return type must be the same as what is defined in the method.
Firstly, take a good look through your code as many of your errors are typos - e.g. toUppercase(), COLLOSAL etc.
And, as per Ben's comment you are using doubles for your constants but then your methods are all integers. Java won't let you do this automatically as it results everything after the decimal point being lost as integers are whole numbers only.
When these two things are changed your code appears to work - at a quick glimpse at least.