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").
Related
This question already has answers here:
What is a StackOverflowError?
(16 answers)
Understanding recursion [closed]
(20 answers)
Closed 3 years ago.
i'm writing a program based on the Quadratic Equation everything looks good to me and there are not syntax or logical errors from what i see and also Eclipse isn't detecting any errors before running.
this is the output from the code:
Exception in thread "main" java.lang.StackOverflowError
at QuadraticEquation.getDiscriminant(QuadraticEquation.java:33)
note it continues like this for about 50 lines or so
public class QuadraticEquation {
private double a;
private double b;
private double c;
public QuadraticEquation() {
double a = 0;
double b = 0;
double c = 0;
}
public QuadraticEquation(double newA, double newB, double newC) {
a = newA;
b = newB;
c = newC;
}
public double discriminant1 = Math.pow(b, 2) - 4 * a * c;
public double discriminant2 = Math.pow(b, 2) - 4 * a * c;
public double getA() {
return getA();
}
public double getB() {
return getB();
}
public double getC() {
return getC();
}
public double getDiscriminant() {
double discriminant = (b * 2) - (4 * a * c);
return getDiscriminant();
}
public double getRoot1() {
double r1 = (-1*b) + Math.sqrt(discriminant1) / (2*a);
return getRoot1();
}
public double getRoot2() {
double r2 = (-1*b) - Math.sqrt(discriminant2) / (2*a);
return getRoot2();
}
public void setA(double newA1) {
a = newA1;
}
public void setB(double newB1) {
b = newB1;
}
public void setC(double newC1) {
c = newC1;
}
}
import java.util.Scanner;
public class TestEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
QuadraticEquation Quadratic = new QuadraticEquation();
System.out.println("Please enter the values of the following variables: ");
System.out.println("a: ");
Quadratic.setA(input.nextDouble());
System.out.println("b: ");
Quadratic.setB(input.nextDouble());
System.out.println("c: ");
Quadratic.setC(input.nextDouble());
if (Quadratic.getDiscriminant() < 0) {
System.out.println("The equation has the following roots:");
System.out.println("The first one is " + Quadratic.getRoot1());
System.out.println("The second one is " + Quadratic.getRoot2());
}
else if (Quadratic.getDiscriminant() == 0) {
System.out.println("The equation has one root:");
System.out.println(Quadratic.getRoot1());
}
else {
System.out.println("The equation has the no real roots");
return;
}
}
}
Your error is an infinite recursion here:
public double getDiscriminant() {
double discriminant = (b * 2) - (4 * a * c);
return getDiscriminant();
}
This function calls itself infinitely until the stack overflows. I believe you wanted to return the variable discriminant instead?
Same for your functions getRoot1, getRoot2, getA, getB, and getC.
As the title says, I cannot convert my ArrayList into an Array. The data type of my ArrayList is a custom object but I cannot seem to find what my problem is. The error that it gives doesn't show up as a problem until the program is run. The first two classes are the objects, then I have a class calle Tester where the main method is.
Class where error appears:
package backend;
import java.util.ArrayList;
public class Function {
Coefficient[] coefArray;
int constant;
public Function(ArrayList<Coefficient> coefFunction, int constant){
Coefficient[] coefArray = (Coefficient[]) coefFunction.toArray();
this.coefArray = sortArray(coefArray);
this.constant = constant;
}
private Coefficient[] sortArray(Coefficient[] newArray){
int tempPow = -1000000000;
Coefficient[] sortedArray = new Coefficient[newArray.length];
sortedArray = null;
for(int i=0; isFull(sortedArray); i++){
for(Coefficient coef : newArray){
if(coef.pow>tempPow){
tempPow = coef.pow;
sortedArray[i] = coef;
}
}
}
return sortedArray;
}
private boolean isFull(Coefficient[] anArray){
for(Coefficient i : anArray) {
if(i == null) return true;
}
return false;
}
public String toString(){
String compiledString="";
for(Coefficient coef : coefArray){
compiledString += coef.toString()+"+";
}
if(constant==0){
//No constant there
}else{
compiledString = compiledString + constant;
}
return compiledString;
}
}
Coefficient Class:
package backend;
public class Coefficient {
String stringVersion;
public int pow;
public int coefInteger;
public double coefDouble;
//Constructor for variable with a coefficient that is non-fractal and a power higher than 1
public Coefficient(int coef, int pow){
this.coefInteger = coef;
this.pow = pow;
switch(coef){
case 0:
//Do nothing here
case 1:
this.stringVersion = "x^"+pow;
break;
default:
this.stringVersion = coef+"x^"+pow;
break;
}
}
//Constructor for variable with a coefficient that is fractal and a power higher than 1
public Coefficient(double coef, int pow){
this.coefDouble = coef;
this.pow = pow;
this.stringVersion = coef+"x^"+pow;
}
//Constructor for variable with a coefficient but no power
public Coefficient(double coef){
this.coefDouble = coef;
this.pow = 1;
this.stringVersion = coef+"x";
}
//Constructor for variable with a coefficient but no power
public Coefficient(int coef){
this.coefInteger = coef;
this.pow = 1;
this.stringVersion = coef+"x";
}
public String toString(){
return stringVersion;
}
}
Tester:
package backend;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Coefficient> function = new ArrayList<Coefficient>();
Coefficient xVal;
Function printFunction;
System.out.println("Enter the degree of the equation:");
int pow = scan.nextInt();
System.out.println("Enter the x components of the function in the order of coefficient then power. Enter constant last:");
double coef = 0;
while(pow>0){
coef = scan.nextDouble();
if(pow==1){
if((int) coef == coef){
xVal = new Coefficient((int) coef);
}else{
xVal = new Coefficient(coef);
}
}else{
if((int) coef == coef){
xVal = new Coefficient((int) coef, pow);
}else{
xVal = new Coefficient(coef, pow);
}
}
function.add(xVal);
pow--;
}
System.out.println("Enter the constant:");
printFunction = new Function(function, scan.nextInt());
System.out.println(printFunction.toString());
}
}
Error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;
cannot be cast to [Lbackend.Coefficient;
at backend.Function.<init>(Function.java:11)
at backend.Tester.main(Tester.java:36)
Any and all help is greatly appreciated. If you see something else that needs to be fixed, please point it out.
The error is in this line:
Coefficient[] coefArray = (Coefficient[]) coefFunction.toArray();
If you read the javadoc of toArray(), you can see that it returns an Object[], which you cannot simply cast to Coefficient[].
Instead use toArray(T[] a):
Coefficient[] coefArray = coefFunction.toArray(new Coefficient[coefFunction.size()]);
Disclaimer: I did not review the rest of your code, so the absence of any remarks does not imply that everything else is fine.
I am trying to get at an area of triangle.
But i have an error that ./ucgenAlanı.java:23: error: missing return statement }
Can you help me ?
import java.util.Scanner;
public class ucgenAlanı {
private double a1,a2,a3;
public void setDimensions( double newa1,double newa2,double newa3 ) {
a1 = newa1;
a2 = newa2;
a3 = newa3;
}
public double readInput() {
Scanner klavye = new Scanner(System.in);
System.out.println(" kenarları giriniz : ");
a1=klavye.nextDouble();
a2=klavye.nextDouble();
a3=klavye.nextDouble();
}
public double getArea() {
double s= (a1 + a2 + a3) / 2;
double area = Math.sqrt( s*(s-a1)*(s-a2)*(s-a3) );
System.out.println( area + "ucgenin alanı" );
return area;
}
}
readInput method doesn't return a double value .
Looking at your code change the method return type to void to fix the problem
Below is the function I am calling, but it returns 0 no matter what I pass.
public static Double calc(double methods, double attributes) {
double a=0;
for (int i=0;i<k;i++) {
for (int j=0;j<l;j++) {
if(matrix[i][j]==1)
a++;
}
}
Double v= new Double( a/(methods*attributes));
System.out.println("The value of v = " + v.doubleValue() );
return v.doubleValue();
}
The System.out statement prints correct value in function but return value prints 0.0.
I took the loop out of your function (all it does is give a value to a). And I added a main (see below).
The return works fine. Maybe the problem is in how you use the return value?
public class Test {
public static Double calc(double methods, double attributes) {
double a=2.0;
Double v= new Double( a/(methods*attributes));
System.out.println("The value of v = " + v.doubleValue() );
return v.doubleValue();
}
public static void main(String [] args) throws Exception
{
Double x = calc(2.0,3.0);
System.out.println(x);
}
}
I have run a demo :
public class demo1{
public static Double calc(double methods, double attributes) {
double a=0;
int k=2;
int l=2;
//int[][] matrix=new int[2][2];
//int
int[][] matrix={{1,2},{2,1},{2,2},{2,2}};
for (int i=0;i<k;i++) {
for (int j=0;j<l;j++) {
if(matrix[i][j]==1)
a++;
}
}
Double v= new Double( a/(methods*attributes));
System.out.println("The value of v = " + v.doubleValue() );
return v.doubleValue();
}
public static void main(String s[]){
Double x = calc(2.0,3.0);
System.out.println(x);
}
}
Output is as follows:
The value of v = 0.3333333333333333
0.3333333333333333
So it is not returning 0.0.
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);