java Mandelbrot set for divergence boundarys - java

My program keeps on getting the red lines of death for the bigNum variable. I am trying to test to see if its in the boundary.
public class ComplexNumber {
private final MyDouble real; // To be initialized in constructors
private final MyDouble imag; // To be initialized in constructors
// constructor initializing
public ComplexNumber(MyDouble realIn, MyDouble imagIn) {
this.real = realIn;
this.imag = imagIn;
}
public ComplexNumber(MyDouble realnumber) {
this.real = realnumber;
this.imag = new MyDouble(0);
}
public MyDouble getReal() {
return real;
}
public MyDouble getImag() {
return imag;
}
// copy constructor
public ComplexNumber(ComplexNumber c) {
this(c.getReal(), c.getImag());
}
// addition of complex numbers
public ComplexNumber add(ComplexNumber a) {
// this.real.add(a.getReal());
return new ComplexNumber(this.real.add(a.getReal()), this.imag.add(a
.getImag()));
}// subtraction of complex numbers
public ComplexNumber subtract(ComplexNumber s) {
return new ComplexNumber(this.real.subtract(s.getReal()), this.imag
.subtract(s.getImag()));
}
// Multiplication of complex numbers
public ComplexNumber multiply(ComplexNumber m) {
MyDouble first = (this.real.multiply(m.getReal()));
MyDouble outside = (m.getReal().multiply(this.imag));
MyDouble inside = (m.getImag().multiply(this.real));
MyDouble last = (this.imag.multiply(m.getImag()));
return (new ComplexNumber(first.subtract(last), (outside.add(inside))));
}
// dividing complex numbers
// double check again but should work
public ComplexNumber divide(ComplexNumber x) {
// MyDouble topReal1 = this.real.multiply(d.getReal());
// MyDouble topReal2 = this.imag.multiply(d.getImag());
// MyDouble topImag1 = this.imag.multiply(d.getReal());
// MyDouble topImag2 = d.getReal().multiply(this.imag);
// MyDouble bottomReal = this.real.multiply(this.real);
// MyDouble bottomImag = d.getImag().multiply(d.getImag());
// MyDouble realSet = topReal1.add(topReal2);
// MyDouble imagSet = topImag1.subtract(topImag2);
// MyDouble top = realSet.add(imagSet);
// MyDouble bottom = bottomReal.add(bottomImag);
//
// return new ComplexNumber(realSet.divide(bottom), imagSet.divide(bottom));
MyDouble demon = x.real.multiply(x.real).add(x.imag.multiply(x.imag));
MyDouble r = real.multiply(x.real).add(imag.multiply(x.imag));
MyDouble i = imag.multiply(x.real).subtract(real.multiply(x.imag));
return new ComplexNumber(r.divide(demon),i.divide(demon));
}
// equals method
public boolean equals(ComplexNumber n) {
return this.real.equals(n.getReal()) && this.imag.equals(n.getImag());
}
// compare to method
//public int compareTo(MyDouble x) {
// int imagNum = x.compareTo(this.getImag());
// int realNum = x.compareTo(this.getReal());
// return realNum + imagNum;
//if ( this.norm(x.equals(x.))
//}
// string to string method
public String toString() {
// thinking how to get negative values since if else didnt work out too
// well
return getReal()+"+"+getImag()+"i";
}
// annoying square root function does not work and api is not as useful
// complex norm method static
public static MyDouble norm(ComplexNumber n) {
MyDouble imag = (n.imag.multiply(n.getImag()));
MyDouble poly = imag.add((n.real.multiply(n.getReal())));
return n.real.multiply(n.real).add(n.imag.multiply(n.imag)).sqrt();
}
// parse method to clear the spaces between the numbers and characters
public static ComplexNumber parse(String s) {
s.replace(" ", "");
String realstring;
String imagstring;
if (s.indexOf('+') != -1) {
realstring = s.substring(0, s.indexOf("+"));
imagstring = s.substring(s.lastIndexOf("+") + 1, s.indexOf("i"));
} else {
realstring = s.substring(0, s.lastIndexOf("-"));
imagstring = s.substring(s.lastIndexOf("-") - 1, s.indexOf("i"));
}
return new ComplexNumber(new MyDouble(Double.parseDouble(realstring)),
new MyDouble(Double.parseDouble(imagstring)));
}
}

If you hover your cursor over the red line in your code or the red circle in the left margin, you should see a more informative error message.
Still, I can take a guess:
I don't know your ComplexNumber class, but I suspect that the multiply and add methods yield ComplexNumber results, and you want a double. I would write your test differently, like so:
double bigNum = aa.getReal() * aa.getReal() + aa.getImag() * aa.getImag();
return (bigNum > Controller.DIVERGENCE_BOUNDARY);

Related

Java setMethod dose not work. When I pass the value to the setMethod it doesn't pass it to line

I have a Result class in which I keep all values/results.
All my code:
public class Main {
public static void main(String[] args) {
Main main = new Main();
Result result = new Result();
Divider divider = new Divider();
String[] myTestArray = new String[]{"1234", "12"};
if (myTestArray.length != 2) {
System.out.printf("You can not use %d arguments. " +
"To perform division, you need to use 2 arguments `", myTestArray.length);`
System.exit(1);
}
int dividend = Integer.parseInt(myTestArray[0]);
int divisor = Integer.parseInt(myTestArray[1]);
divider.divide(dividend, divisor);
Formatter formatter = new Formatter();
formatter.format(result);
}
}
public class Divider {
Result result;
public Divider() {
this.result = new Result();
}
/**
* divide method performs division of two numbers
*/
public void divide(int dividend, int divisor) {
result.setDividend(Math.abs(dividend));
result.setDivisor(Math.abs(divisor));
result.setQuotient(divideTwoNumbers(result.getDividend(),
result.getDivisor()));
}
/**
*
*/
public int calculateProduct(int partialDividend) {
int multiplicand = divideTwoNumbers(partialDividend, `result.getDivisor());`
result.setProduct(multipleTwoNumbers(result.getDivisor(), `multiplicand));`
result.setRemainder(partialDividend - result.getProduct());
return result.getProduct();
}
/**
* Method divideTwoNumbers is used instead of operands "/"
*/
public int divideTwoNumbers(int dividend, int divisor) {
int result = 0;
for (int i = 0; dividend >= divisor; i++) {
dividend = dividend - divisor;
result++;
}
return result;
}
/**
* Method multipleTwoNumbers is used instead of operands "*"
*/
public int multipleTwoNumbers(int multiplicand, int multiplier) {
int product = 0;
for (int i = 0; i < multiplicand; i++) {
product = product + multiplier;
}
return product;
}
}
I think, my problem is around here somewhere
public class Formatter {
Result result;
Divider divider;
private int firstIndexPartialDividend = 0; // find the beginning of the number
private int countSpace = 0; // space counter
public Formatter() {
this.result = new Result();
this.divider = new Divider();
}
public void format() {
// print the first row
printFirstRow();
String dividendText = Integer.toString(result.getDividend());
for (int i = 1; i <= dividendText.length(); i++) {
result.setFirstPartialDividend(Integer.parseInt
(dividendText.substring(firstIndexPartialDividend, i)));
// print the second row
if (result.getFirstPartialDividend() >= result.getDivisor() &&
firstIndexPartialDividend == 0) {
countSpace = dividendText.length() - i;
printSecondRow(result.getFirstPartialDividend());
firstIndexPartialDividend = i;
// To align the space in the next row.
if (Integer.toString(result.getProduct()).length()
> Integer.toString(result.getRemainder()).length() &&
result.getRemainder() > 0) {
countSpace = Integer.toString(result.getProduct()).length()
- Integer.toString(result.getRemainder()).length();
} else {
countSpace = 0;
}
}
}
}
/**
* printFirstRow method - print the first row of an application
*/
public void printFirstRow() {
System.out.printf("%d|%d\n", result.getDividend(), `enter code here`result.getDivisor());
}
/**
* printSecondRow method - print the second row of an application
*/
public void printSecondRow(int firstPartialDividend) {
divider.calculateProduct(firstPartialDividend);
System.out.println(result.getProduct() + getSpace(countSpace) + `enter code here`"|" + (result.getQuotient()));
}
/**
* getSpace method to get the number of spaces you want
*/
public String getSpace(int count) {
String space = "";
for (int i = 0; i < count; i++)
space += " ";
return space;
}
}
public class Result {
private int quotient; // keep the result of division
private int dividend;
private int divisor;
private int firstPartialDividend; //keep the result of division the `enter code here`first partial dividend
private int product;
private int remainder;
`enter code here`public Result() {
this.dividend = dividend;
this.divisor = divisor;
}
public int getQuotient() {
return quotient;
}
public void setQuotient(int quotient) {
this.quotient = quotient;
}
public int getDividend() {
return dividend;
}
public void setDividend(int dividend) {
this.dividend = dividend;
}
public int getDivisor() {
return divisor;
}
public void setDivisor(int divisor) {
this.divisor = divisor;
}
public int getFirstPartialDividend() {
return firstPartialDividend;
}
public void setFirstPartialDividend(int firstPartialDividend) {
this.firstPartialDividend = firstPartialDividend;
}
public int getProduct() {
return product;
}
public void setProduct(int product) {
this.product = product;
}
public int getRemainder() {
return remainder;
}
public void setRemainder(int remainder) {
this.remainder = remainder;
}
}
values are still 0
My program should print long division result
Like this:
1234|12
12 |102
34
24
10
Of course this is not the whole program, I am still working on it.
The image shown has stopped before the assignment is complete. The parameter value is 1234, and the current value of this.dividend is zero. If you step the debugger forward, both will have the value of 1234
Your setters are working fine. You are just not calling the setters on the correct instances.
Regarding the "issue". You have a Result and Divider instance in main method that is not given to the Formatter. When you create a new Formatter() it has its own instances that are initialized with the default values of zero.
You probably should have a constructors that carry through the same instances. For example
Result result = new Result(); // this probably isn't even needed
Divider divider = new Divider(result); // param could be removed
divider.divide(x1, x2); // This method could create and store `new Result()` value on its own
Formatter formatter = new Formatter(divider, result); // again, result not needed since it would be internal to the divider
formatter.format();
(and your formatter should probably only "format the result" as the name implies instead of also doing calculations with the Divider instance)
You can also remove new Main() since that isn't doing anything
OneCricketeer - thanks a lot!!!
I has changed constructor Divider and Formatter.
Result result = new Result();
Divider divider = new Divider(result);
divider.divide(dividend, divisor);
Formatter formatter = new Formatter(result);
formatter.format();
public Divider(Result result) {
this.result = result;
}
public Formatter(Result result) {
this.result = result;
this.divider = new Divider(result);
}
Now my output is
1234|12
12 |102

Calculator for metric distance from an expression that contains different scales

public enum Operator {
PLUS("+"),
MINUS("-");
private final String operator;
Operator(String operator) {
this.operator = operator;
}
public String getOperator() {
return operator;
}
public static Operator getByValue(String operator) {
for (Operator operatorEnum : Operator.values()) {
if (operatorEnum.getOperator().equals(operator)) {
return operatorEnum;
}
}
throw new IllegalArgumentException("Invalid value");
}
}
//////////
public enum MetricConvertor {
m(1000),
cm(10),
mm(1),
km(1000000),
dm(100);
private int scale;
MetricConvertor(int scale) {
this.scale = scale;
}
public int getScale() {
return scale;
}
}
/////////
public class Application {
public static void main(String[] args) {
int scale = MetricConvertor.valueOf("m").getScale();
}
I wan to create a calculator that is capable of computing a metric distance value from an expression that contains different scales and systems.
Output should be specified by the user.
Only Addition and subtraction is allowed.
Output is in lowest unit.
Expression: 10 cm + 1 m - 10 mm
Result: 1090 mm
I am stuck at this point, how can I add or substract the values for a list and convert them at the lowest scale sistem( eg above mm, but it can be dm if are added for example dm + m + km)
Here is solution
split each string by add/minus and add it to appropriate list
split number and metric in each list(can use matcher) and sum it
result = sumAdd - sumMinus(mm).
Please optimize it, because i don't have time to optimize this code, I need to go to bed :D
Result is in mm, so you have to get lowest metric and recaculate it(leave it to you).
private static int caculator(String exp) {
List<String> addList = new ArrayList<>();
List<String> minusList = new ArrayList<>();
int checkPoint = 0;
boolean op = true;//default first value is plus
// Split string with add/minus
for (int i = 1; i < exp.length(); i++) {
String s = exp.substring(i, i + 1);
if (Operator.PLUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = true;
continue;
}
if (Operator.MINUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = false;
continue;
}
}
// Add last string
checkOperator(addList, minusList, op, exp.substring(checkPoint).trim());
// Get sum each list
int sumAdd = sumList(addList);
int sumMinus = sumList(minusList);
return sumAdd - sumMinus;
}
//sum a list
private static int sumList(List<String> addList) {
int sum = 0;
for (String s: addList) {
String[] arr = s.split(" ");
int value = Integer.parseInt(arr[0]);
int scale = MetricConvertor.valueOf(arr[1]).getScale();
sum += value * scale;
}
return sum;
}
// check operator to put into approriate list
private static void checkOperator(List<String> addList, List<String> minusList, boolean op, String substring) {
if (op) {
addList.add(substring);
} else {
minusList.add(substring);
}
}

why is calculator.getValue() always 0?

I am a java student and I am working to make my code more object oriented. I can easily code calculator in main but I'm really struggling to implement it with methods. The following code will always return 0...but the goal is to create a program which allows a user to enter an operator and a number in one line (example +5) the code should output the previous value, the new value, and allow for resetting. I believe I am really close to solving this and just need a point in the right direction..
output
Enter an operator and a number:
+5
0.0
Calculator class
import java.util.Scanner;
public class Calculator {
private final int RESET = 0;
private double number = 0;
private double result = 0; // I believe this is the issue but how can I resolve it?
private char operator;
private static Scanner keyboard = new Scanner(System.in);
public Calculator(double number)
{
this.number = number;
}
// this method invokes the whatOperator() to create a new result
// the edited method still returns 0
public double aResult(Calculator other)
{
other.whatOperator();
this.result = other.result;
return result;
}
// I created this method in hopes that it would do most of the work..when I invoke it and enter my operator and number it does not seem to function correctly
public void whatOperator()
{
String operator = null;
operator = enterNumber();
double theNumber = Double.parseDouble(operator);
char theOperator =operator.charAt(0);
operator = null;
operator += theOperator;
// switch method to find the operator
switch(operator){
case "*":
result = getNumber() * theNumber;
break;
case "/":
result = getNumber() / theNumber;
break;
case "+":
result = getNumber() + theNumber;
break;
case "-":
result = getNumber() - theNumber;
break;
case "R":
result = RESET;
break;
}
}
// methods for operation...I was hoping to not use these
public double add(double secondNumber)
{
result = number + secondNumber;
return result;
}
public double divide(double secondNumber)
{
result = number / secondNumber;
return result;
}
public double multiply(double secondNumber)
{
result = number * secondNumber;
return result;
}
public void subtract(double secondNumber)
{
result = number - secondNumber;
}
public double getNumber()
{
return number;
}
// method for getting input
public static String enterNumber()
{
System.out.println("Enter an operator and a number:");
String toString = keyboard.nextLine();
return toString;
}
public static void main (String[] args) {
// the calculator is initialized at 0
Calculator a = new Calculator(0);
// now I create a second calculator with the result from the aResult()
Calculator b = new Calculator(a.aResult(a));
// why is b.getNumber() = 0 at this point?
String theString = String.valueOf(b.getNumber());
// prints 0 every time
System.out.println(theString);
}
}
There are some mistakes in your code.
public double aResult(Calculator other)
{
other = new Calculator(getNumber());
other.whatOperator();
this.result = result;
return result;
}
The line this.result = result doesn't make any sense. I think you wanted the method whatOperator() to return a result e.g.
this.result = other.whatOperator();
I also think that you don't want to override the "other" calculator. You never use the new calculator. But you want to print the output of the new calculator in your main method. Because you never used the new calculator, the output is 0.
In your aResult method you are initiating another new instance of Calculator
public double aResult(Calculator other) {
//other = new Calculator(getNumber()); // this should not be here
other.whatOperator();
this.result = result;
return result;
}
The solution to the problem:
//change
this.result = result; //this does nothing
//to
this.result = other.result; //this changes the result to the new value
//erase this line
other = new Calculator(getNumber()); // do not need to create a new calculator
change the method whatOperator to a double and return a double with it

How to print out a toString for this class?

I have written a polynomial class and a tester class. The polynomial class can evaluate and return the sum of the polynomial when the degree, coefficients and the value of x are provided. Basically I need to edit my toString method so it actually prints out the polynomial
import java.util.Arrays;
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
private double value;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient)
{
this.coefficient[this.degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public double Evaluate(double value)
{
this.value =value;
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
return sum;
}
/** Standard toString method */
//needed something better than this below...needed an actual polynomial printed out
public String toString()
{
return "The degree of the polynomial is " + degree + " and the value for which it has been evaluated is" + value;
}
}
This should be along the lines you should be proceeding. I included the main function in your Polynomial class for simplicity, so you will have to modify that if you want to keep it in your tester class. Notice that degree has been made into an integer array of size degree +1(allocated in the constructor):
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient, int degree)
{
this.coefficient[degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
}
public double getSum(){
return sum;
}
public String toString()
{
String s = "";
for (int i=0; i <= degree; i++)
{
s += coefficient[i];
switch (i) {
case 0:
s += " + ";
break;
case 1:
s += "x + ";
break;
default:
s += "x^" + i + ((i==degree)?"":" + ");
}
}
return s;
}
public static void main(String[] args) {
int degree;
double sum;
int coefficient;
Scanner key = new Scanner(System.in);
System.out.println("Enter the degree of the polynomial");
degree=key.nextInt();
Polynomial fun = new Polynomial(degree);
fun.Evaluate(3.0);
System.out.println(" The sum of the polynomial is " + fun.getSum());
System.out.println(fun);
}
}
The usual way of making the objects of a class printable is to supply a toString method in the class, which specifies how to express objects of that class as a String. Methods such as println and other ways of outputting a value will call a class's toString method if they need to print an object of that class.
You should adopt the same pattern with your Polynomial class - write a toString method with all the output logic. Then in your PolynomialTester class, all you need to write is System.out.println(fun); and the rest will just happen. You'll find this far more versatile than writing a method that actually does the printing. For example, you'll be able to write something like
System.out.println("My polynomial is " + fun + " and " + fun + " is my polynomial.");
if that's your idea of fun.
A few other things concern me about your class.
You seem to be only storing one coefficient and one exponent. I'd expect a polynomial to have a whole array of coefficients.
You have fields for evaluation and sum - but these only really make sense while a polynomial is being evaluated. They're not long-term properties of the polynomial. So don't store them in fields. Have them as local variables of the evaluate method, and return the result of the evaluation.
I'd expect a class like this to be immutable. That is, you should provide all the coefficients when the object is created, and just never change them thereafter. If you do it that way, there's no need to write setter methods.
So I've written my own version of your class, that fixes those issues listed above, and implements a toString method that you can use for printing it. A second version of toString lets you specify which letter you want to use for x. I've used "varargs" in the constructor, so you can construct your polynomial with a line such as
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
specifying the coefficients from the constant term through in order to the coefficient of the term with the highest exponent. Or you can just pass an array.
See that I've changed the logic a wee bit - my version prints the polynomial in the conventional order, from highest to lowest exponent. It leaves off the decimals if the coefficient is an integer. It doesn't print a 1 in front of an x. And it deals cleanly with - signs.
import java.util.Arrays;
public class Polynomial {
private double[] coefficients;
public Polynomial(double... coefficients) {
this.coefficients = Arrays.copyOf(coefficients, coefficients.length);
}
public int getDegree() {
int biggestExponent = coefficients.length - 1;
while(biggestExponent > 0 && coefficients[biggestExponent] == 0.0) {
biggestExponent--;
}
return biggestExponent;
}
public double getCoefficient(int exponent) {
if (exponent < 0 || exponent > getDegree()) {
return 0.0;
} else {
return coefficients[exponent];
}
}
public double evaluateAt(double x) {
double toReturn = 0.0;
for (int term = 0; term < coefficients.length; term++) {
toReturn += coefficients[term] * Math.pow(x, term);
}
return toReturn;
}
#Override
public String toString() {
return toString('x');
}
public String toString(char variable) {
boolean anythingAppendedYet = false;
StringBuilder toReturn = new StringBuilder();
for (int exponent = coefficients.length - 1; exponent >= 0; exponent--) {
if (coefficients[exponent] != 0.0) {
appendSign(toReturn, exponent, anythingAppendedYet);
appendNumberPart(toReturn, exponent);
appendLetterAndExponent(toReturn, exponent, variable);
anythingAppendedYet = true;
}
}
if (anythingAppendedYet) {
return toReturn.toString();
} else {
return "0";
}
}
private void appendSign(StringBuilder toAppendTo, int exponent, boolean anythingAppendedYet) {
if (coefficients[exponent] < 0) {
toAppendTo.append(" - ");
} else if (anythingAppendedYet) {
toAppendTo.append(" + ");
}
}
private void appendNumberPart(StringBuilder toAppendTo, int exponent) {
double numberPart = Math.abs(coefficients[exponent]);
if (numberPart != 1.0 || exponent == 0) {
//Don't print 1 in front of the letter, but do print 1 if it's the constant term.
if (numberPart == Math.rint(numberPart)) {
// Coefficient is an integer, so don't show decimals
toAppendTo.append((long) numberPart);
} else {
toAppendTo.append(numberPart);
}
}
}
private void appendLetterAndExponent(StringBuilder toAppendTo, int exponent, char variable) {
if (exponent > 0) {
toAppendTo.append(variable);
}
if (exponent > 1) {
toAppendTo.append("^");
toAppendTo.append(exponent);
}
}
}
So I tested it with this class
public class PolynomialTester {
public static void main(String[] args) {
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
System.out.println(fun.getDegree());
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
}
}
and the output was
4
139.0
x^4 + 5x^2 + 2x + 7
then I realised that you wanted to be able to input the coefficients in a loop. So I changed PolynomialTester to this. See how I build the array and then create the object.
import java.util.Scanner;
public class PolynomialTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the degree:");
int degree = input.nextInt();
double[] coefficients = new double[degree + 1];
for( int exponent = 0; exponent <= degree; exponent++) {
System.out.println("Enter the coefficient of x^" + exponent);
coefficients[exponent] = input.nextDouble();
}
Polynomial fun = new Polynomial (coefficients);
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
input.close();
}
}
Note that if you really want your polynomial to be printed in "reverse" order, with the constant term first, you could change the loop in the toString method to this.
for (int exponent = 0; exponent < coefficients.length; exponent++) {
You may add a class member String poly, then modify the following method.
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient= key.nextInt();
evaluation = Math.pow(value, i)*coefficient ;
this.sum += evaluation;
this.poly = "";
if(coefficient != 0)
{
if(i > 0)
{
this.poly += " + " + Integer.toString(coefficient) + "x^" + Integer.toString(i); // you may replace x with the actual value if you want
}
else
{
this.poly = Integer.toString(coefficient)
}
}
}
}

Using an ArrayList to output perimeters of triangles

I'm trying to write a program that takes in the different sides of a triangle, error-checks to make sure they would be valid, and then outputs them using an ArrayList.
I want it to look something like this...
"Perimeter of triangle t1 is 24."
"Perimeter of triangle t2 is 30"
The ArrayList is my main issue here, I think (probably have more issues). Below, I just tried my best to implement the ArrayList, but obviously couldn't get it. Also, how would I write/change my toString function, so that it would also contain the name of the object created in main (i.e. t1, t2, etc.)?
Thanks for looking!
import java.util.*;
public class Tri {
public static void main(String []args){
Triangle t1 = new Triangle(7, 5, 4);
Triangle t2 = new Triangle(9, 6, 1);
System.out.println(t1.perimeter());
System.out.println(t2.perimeter());
ArrayList<Triangle>allTriangles = new ArrayList<Triangle>();
}
public static double totalPerimeter( ArrayList<Triangle>a ){
System.out.println(Arrays.toString( a.toArray()));
for( int i = 0; i < a.length; i++){
System.out.println( a.perimeter[i]);
}
}
class Triangle{
public Triangle( double a, double b, double c ){
this.sideA = a;
this.sideB = b;
this.sideB = c;
if (checkSides() == true){}
}
public double getA(){
return sideA;
}
public double getB(){
return sideB;
}
public double getC(){
return sideC;
}
public Triangle setA( double a ){
sideA = a;
return this;
}
public Triangle setB( double b ){
sideB = b;
return this;
}
public Triangle setC( double c ){
sideC = c;
return this;
}
public String toString(){
return "Perimeter of triangle is " + perimeter;
}
public double perimeter(){
if (checkSides() == true)
perimeter = (sideA+sideB+sideC);
return perimeter;
}
private boolean checkSides(){
if (!(sideA+sideB>sideC) && (sideA+sideC>sideB) && (sideB+sideC>sideA)){
die("Not valid sides of triangle.");
return false;
}
else return true;
}
public void die( String msg ){
System.err.println( "\nFatal error: " + msg );
System.exit( 1 );
}
private double perimeter;
private double sideA;
private double sideB;
private double sideC;
}
Here is what your code should be:
import java.util.*;
public class Tri {
public static void main(String []args){
Triangle t1 = new Triangle(7, 5, 4);
Triangle t2 = new Triangle(9, 6, 1);
System.out.println(t1.perimeter());
System.out.println(t2.perimeter());
ArrayList<Triangle>allTriangles = new ArrayList<Triangle>();
allTriangles.add(t1);
allTriangles.add(t2);
System.out.println(totalPerimeter(allTriangles));
}
public static double totalPerimeter( ArrayList<Triangle>a ){
double tp = 0.0;
for(Triangle t : a) {
System.out.println( "peri : " + t.perimeter());
tp += t.perimeter();
}
return tp;
// for( int i = 0; i < a.length; i++){
//
// System.out.println( a.perimeter[i]);
//
// }
}
static class Triangle{
public Triangle( double a, double b, double c ){
this.sideA = a;
this.sideB = b;
this.sideB = c;
if (checkSides() == true){}
}
public double getA(){
return sideA;
}
public double getB(){
return sideB;
}
public double getC(){
return sideC;
}
public Triangle setA( double a ){
sideA = a;
return this;
}
public Triangle setB( double b ){
sideB = b;
return this;
}
public Triangle setC( double c ){
sideC = c;
return this;
}
public String toString(){
return "Perimeter of triangle is " + perimeter;
}
public double perimeter(){
if (checkSides() == true)
perimeter = (sideA+sideB+sideC);
return perimeter;
}
private boolean checkSides(){
if (!(sideA+sideB>sideC) && (sideA+sideC>sideB) && (sideB+sideC>sideA)){
die("Not valid sides of triangle.");
return false;
}
else return true;
}
public void die( String msg ){
System.err.println( "\nFatal error: " + msg );
System.exit( 1 );
}
private double perimeter;
private double sideA;
private double sideB;
private double sideC;
}
}
In your totalPerimeter function:
Since a is of type ArrayList, it doesn't have a length attribute. It does however have a size() method. Reference: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html.
Since a is of type ArrayList, it does not have a perimeter array field. Did you perhaps mean something like a.get(i).perimeter()?
First Question:
The ArrayList is my main issue here, I think (probably have more
issues). Below, I just tried my best to implement the ArrayList, but
obviously couldn't get it.
Well, it seems you are missing the return statement and have a logical issue in your totalPerimeter(...) method. You need to make sure to add the total perimeter up in a variable, then return that variable. Also, ArrayList use the method size() for length of the list instead of length. Also, you access ArrayList objects using the get(...) method.
public static double totalPerimeter( ArrayList<Triangle>a ){
double total = 0.0; //give default value of 0
for( int i = 0; i < a.size(); i++){
total = total + a.get(i).perimeter(); //add up total
}
return total;//return it back!
}
Second Question:
Also, how would I write/change my toString function, so that it would
also contain the name of the object created in main (i.e. t1, t2,
etc.)?
I don't think you can do that. However, you could pass a String to the constructor:
private String name;
public Triangle( double a, double b, double c, String variableName){
this.sideA = a;
this.sideB = b;
this.sideB = c;
this.name = variableName;
if (checkSides() == true){}
}
Then in your main:
Triangle t1 = new Triangle(7, 5, 4, "t1");
Triangle t2 = new Triangle(9, 6, 1, "t2");
You can then update your toString(...) method and access the variable name.
Note: Final thing to note is that when you checkSides() and it returns false. You should throw an Exception or give the user a warning (ex. print out "WARNING: invalid sides").

Categories

Resources