Java program stops working without warning - java

I created a method:
public double Calculouno(double x1,double x2,double y1,double y2)
{
double ecuacion1;
ecuacion1= (x2-x1)+(y2-y1);
ecuacion1= Math.sqrt(ecuacion1);
return ecuacion1;
}
When my program tries to calculate ecuacion1 using mathematical functions such as pow and sqrt (at least that´s what I suspect), it just stops working without a compiler warning and says "Build succesful". Help please.
When i reach this part (method), the compiler says "Build succesful" and it just ends. My program works great until this part.
This is the entire source code.
import java.util.Scanner;
import java.lang.Math;
public class Ejercicio12
{
public static void main(String args[])
{
double[] x= new double[3];
double[] y= new double[3];
double a,b,c;
int con=0, con2=0;
double[] angulo= new double[3];
Scanner entrada = new Scanner(System.in);
Calculos cal= new Calculos();
for(con=0;con<3;con++)
{
System.out.println("Ingrese un valor x para el punto "+(con+1)+": ");
x[con]= entrada.nextDouble();
System.out.println("Ingrese un valor y para el punto "+(con+1)+": ");
y[con]= entrada.nextDouble();
}
a= cal.Calculouno(x[0],x[1],y[0],y[1]);
b= cal.Calculouno(x[1],x[2],y[1],y[2]);
c= cal.Calculouno(x[2],x[0],y[2],y[0]);
angulo[0]= cal.Angulo(a,b,c);
angulo[1]= cal.Angulo(c,a,b);
angulo[2]= cal.Angulo(b,a,c);
if(angulo[0]>90||angulo[1]>90||angulo[2]>90)
{
System.out.println("El triangulo es obtusangulo");
}
else
{
if(angulo[0]==90||angulo[1]==90||angulo[2]==90)
{
System.out.println("El triangulo es rectangulo");
}
else
{
if(angulo[0]<90&&angulo[1]<90&&angulo[2]<90)
{
System.out.println("El triangulo es acutangulo");
}
}
}
}
}
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
import static java.lang.Math.acos;
public class Calculos
{
public double Calculouno(double x1,double x2,double y1,double y2)
{
double ecuacion1;
double dx= (x2-x1);
double dy= (y2-y1);
return Math.sqrt(dy+dx);
}
public double Angulo(double a1,double b1, double c1)
{
double ecuacion2;
double a11 = pow(a1,2);
double b11 = pow(b1,2);
double c11 = pow(c1,1);
double xx=(b11+c11-a11);
double zz=(2*b1*c1);
return Math.acos(xx/zz);
}
}

There is nothing in the code in your snippet that will (directly) cause the program to "stop without warning".
There are no syntax errors (etcetera) that would cause a build to fail. (And that matches what you report.)
Giving "bad" input to Math.sqrt won't cause it to stop, or even throw an exception. The javadoc says: "[Returns] the positive square root of a. If the argument is NaN or less than zero, the result is NaN." i.e. bad input will give you a NaN value.
Bad input wouldn't cause the arithmetic before the sqrt call to throw exceptions. The JLS says (for the floating point + and - operators) "[i]f either operand is NaN, the result is NaN."
So the immediate cause of your application's stopping must be somewhere else in your application.
I expect that what is happening is that some other part of your code is throwing an exception when it gets an unexpected result from this method (maybe a NaN) ... and your application is squashing the exception.
I understand the problem now.
What is happening is that the arithmetic and/or calls to sqrt and pow >>are<< generating NaN values. When you test a NaN value using any of the relational operators, the result of the expression is always false. So that means that your code that none of the println calls is made.
Your code is not actually stopping. Rather it is completing normally without producing any output.
And the underlying reason that the calculations are producing NaN values is ... as #duffymo has pointed out ... that you have implemented the geometric formulae incorrectly.
For the record, NaN values have peculiar behaviour when they are used in a relation expressions. For instance:
double x = 0.0 / 0.0; // generate a NaN
System.out.println(0.0 == x);
System.out.println(0.0 != x);
System.out.println(0.0 < x);
System.out.println(0.0 > x);
System.out.println(x == x);
System.out.println(x != x);
System.out.println(x < x);
System.out.println(x > x);
All will of the above will print "false". Yes, all of them!
The only way to test for a NaN is to use Double.isNaN(double) or Float.isNaN(float).

Here are two links that I believe describe the problem you want to solve pretty well:
http://mathworld.wolfram.com/AcuteTriangle.html
and
http://mathworld.wolfram.com/ObtuseTriangle.html
Here's how I might write it. I didn't test it exhaustively:
package cruft;
/**
* Junk description here
* #author Michael
* #link
* #since 9/8/12 10:19 PM
*/
public class Triangle {
private final Point p1;
private final Point p2;
private final Point p3;
public static void main(String args[]) {
if (args.length > 5) {
Point p1 = new Point(Double.valueOf(args[0]), Double.valueOf(args[1]));
Point p2 = new Point(Double.valueOf(args[2]), Double.valueOf(args[3]));
Point p3 = new Point(Double.valueOf(args[4]), Double.valueOf(args[5]));
Triangle triangle = new Triangle(p1, p2, p3);
double angle = triangle.calculateAngle();
System.out.println(triangle);
if (angle > 0.0) {
System.out.println("obtuse");
} else if (angle < 0.0) {
System.out.println("acute");
} else {
System.out.println("right triangle");
}
} else {
System.out.println("Usage: Triangle x1 y1 x2 y2 x3 y3");
}
}
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public double calculateAngle(){
double a = Point.distance(this.p1, this.p2);
double b = Point.distance(this.p2, this.p3);
double c = Point.distance(this.p3, this.p1);
return Math.acos(a*a + b*b - c*c)/2.0/a/b;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Triangle");
sb.append("{p1=").append(p1);
sb.append(", p2=").append(p2);
sb.append(", p3=").append(p3);
sb.append('}');
return sb.toString();
}
}
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public static double distance(Point q1, Point q2) {
double dx = Math.abs(q1.x-q2.x);
double dy = Math.abs(q1.y-q2.y);
if (dx > dy) {
double r = dy/dx;
return dx*Math.sqrt(1.0+r*r);
} else {
double r = dx/dy;
return dy*Math.sqrt(1.0+r*r);
}
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append('(').append(x);
sb.append(',').append(y);
sb.append(')');
return sb.toString();
}
}

Related

Trouble with Method undefined for a type Java

I'm new to Java programming and having a hard time understanding the use of methods and how to use them in the code. I know this is really basic things and I'm trying, it's just hard to grasp at first. So tl;dr I don't quite understand this error or how to fix it.
public class TriangleInfo {
public static void main(String args[]) {
Triangle versuch = createTriangle();
}
public static createTriangle() {
double side1 = 90;
double side2 = 80;
double hypotenuse = getHypotenuse();
Triangle thisTriangle = new Triangle(side1, side2, hypotenuse);
return thisTriangle;
}
public static double getHypotenuse() {
return Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
}
}
The error I'm getting is:
The method createTriangle() is undefined for the type TriangleInfo
I also have this written in another file:
public class Triangle {
double side1;
double side2;
double hypotenuse;
// Konstrukturen
public Triangle(double sideOne, double sideTwo, double hypotenuse) {
this.sideOne = sideOne;
this.sideTwo = sideTwo;
this.hypotenuse = hypotenuse;
}
}
Could someone please help me understand this error and how to correct it? Thank you!
The error is that your method createTriangle() doesn't have a return type. Since you are returning a Triangle, you need to add that.
public static Triangle createTriangle() {
And continue with your normal code.
Also, a good catch from #JO3-W3B-D3V, the side1 and side2 are not globally accessible in the class, so you need to do:
public static double getHypotenuse(double side1, double side2) {
return Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
}
So, your complete createTriangle() function becomes:
public static Triangle createTriangle(){
double side1 = 90;
double side2 = 80;
double hypotenuse = getHypotenuse(side1, side2);
Triangle thisTriangle = new Triangle(side1, side2, hypotenuse);
return thisTriangle;
}
Okay, first of all, looking at the code you've provided, the method createTriangle does not have a return type specified, all you need to do here is refactor it like so:
public static Triangle createTriangle() { // Body of the method...
Then there's the matter of the getHypotenuse method, since it has no reference to the values side1 or side2, you need to either alter it such that the these variables are properties within the class, or you can update the method & the caller, like so:
Caller
double hypotenuse = getHypotenuse(side1, side2);
Method
public static double getHypotenuse(double side1, double side2) { // Body of the method...
Finally, in the Triangle class, you have the property names stated as side, but in the constructor of the Triangle class, you try to assign this.sideOne, it should either be side1 in the constructor, or you should change the name(s) of the class properties.
Summary
To be fair, I appreciate that you're a beginner & to be fair, you weren't too far from having a working implementation.
Complete Solution
import java.lang.Math;
public class TriangleInfo {
public static void main(String args[]) {
Triangle versuch = createTriangle();
}
public static Triangle createTriangle() {
double side1 = 90;
double side2 = 80;
double hypotenuse = getHypotenuse(side1, side2);
Triangle thisTriangle = new Triangle(side1, side2, hypotenuse);
return thisTriangle;
}
public static double getHypotenuse(double side1, double side2) {
return Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2));
}
}
class Triangle {
double side1;
double side2;
double hypotenuse;
// Konstrukturen
public Triangle(double sideOne, double sideTwo, double hypotenuse) {
this.side1 = sideOne;
this.side2 = sideTwo;
this.hypotenuse = hypotenuse;
}
}

converting decimal into fractions, java and python gives different output

i'm trying to convert decimals into fractions. my program works just fine for other numbers. however when trying to find the numerator and denominator for 1.0923059908040425e-33,
java gives 1/9
where as python gives 0.
this is my code for java:
class Rational {
public static void main(String[] args) {
println(getDenominator(convertDecimalToFraction(1.0923059908040425e-33)));
}
public static int getNumerator(String fraction) {
return Integer.valueOf(fraction.substring(0, fraction.indexOf(".")));
}
public static int getDenominator(String fraction) {
fraction = fraction.substring(fraction.indexOf("/") + 1);
return Integer.valueOf(fraction.substring(0, fraction.indexOf(".")));
}
static private String convertDecimalToFraction(double x){
if (x < 0){
return "-" + convertDecimalToFraction(-x);
}
double tolerance = 1.0E-6;
double h1=1; double h2=0;
double k1=0; double k2=1;
double b = x;
do {
double a = Math.floor(b);
double aux = h1; h1 = a*h1+h2; h2 = aux;
aux = k1; k1 = a*k1+k2; k2 = aux;
b = 1/(b-a);
} while (Math.abs(x-h1/k1) > x*tolerance);
return h1+"/"+k1;
}
}
and this is python:
print(fractions.Fraction(1.0923059908040425e-33).limit_denominator())
i think there's problem in my java code because i'm expecting 0 as correct output, but there is built-in library available for Fractions, and i don't want to use any third-party libraries.
java code works on mostly all inputs. only problem with this one input. please point me error if any.
i would really appreciate if you can provide me with a method or logic that can solve this problem
print(fractions.Fraction(1.0923059908040425e-33)) gives 6385627976105849/5846006549323611672814739330865132078623730171904
after adding limit_denominator, it becomes 0.
i don't know what is going on here..
Well a bit a debugging would immediately show what happens. convertDecimalToFraction returns "1.0/9.15494383825455E32" which is not stupid, but getDenominator just ignores the E32. You should mimic the limit_denominator from Python and say that if x<tolerance then the returned value shall be "0./1.":
static private String convertDecimalToFraction(double x){
if (x < 0){
return "-" + convertDecimalToFraction(-x);
}
double tolerance = 1.0E-6;
if (x < tolerance) {
return "0./1.";
}
double h1=1; double h2=0;
double k1=0; double k2=1;
double b = x;
do {
double a = Math.floor(b);
double aux = h1; h1 = a*h1+h2; h2 = aux;
aux = k1; k1 = a*k1+k2; k2 = aux;
b = 1/(b-a);
} while (Math.abs(x-h1/k1) > x*tolerance);
return h1+"/"+k1;
}

why my java code fails when i'm trying to typecast inside try block?

I've written the code this way where the method division returns double value after dividing two integers.It works fine if i do not include try catch block.But when I enclose the integer division with type casting inside try block as shown below, it leads to compilation problem... please solve my problem.
import java.util.Scanner;
class Division {
/**
* #param args
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Division div=new Division();
System.out.println("Enter the two numbers to perform division operation:");
int x=sc.nextInt();
int y=sc.nextInt();
div.division(x,y);
}
public double division(int x,int y){
try{
double z=(double)(x/y);
return z;
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
}
}
You are missing a return in your division function. By catching the exception you are saying that you are going to do something to handle it in the case that there is an issue and execution will continue after.
It would probably be best to just throw the exception here because if you divide by zero there will be nothing to return. Optionally you could return something nonsensical like -1
public double division(int x,int y){
try{
double z=(double)(x/y);
return z;
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
return -1;
}
An even better solution would be to throw an exception if the divisor is 0 and then handle it wherever it is used
public double division(int x, int y) throws ArithmeticException {
if (y == 0)
throw new ArithmeticException("Cannot divide by 0");
double z = (double) (x / y);
return z;
}
Your method missing the return statement. Try this one
public double division(int x,int y){
double z=0.0;
try{
z=(double)(x/y);
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
return z;
}
Your method must have a return statement.
Your current code don't have return statement if it enters the catch block.
Try this code.
import java.util.Scanner;
public class Division {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Division div = new Division();
System.out.println("Enter the two numbers to perform division operation:");
int x = sc.nextInt();
int y = sc.nextInt();
div.division(x, y);
}
public double division(int x, int y) {
double z = 0;
try {
z = (double) (x / y);
} catch (ArithmeticException ae) {
ae.printStackTrace();
}
return z;
}
}
Live Demo here.
Also I guess there is data loss in the way you are type-casting.
If 17/3 = 5.6666666 is what you want, then your code is WRONG because x and y are int. The output you will get with the current code is 17/3=5
Instead of z = (double) (x / y);, you need z = (double) x / (double) y;
The issue is that if your try block fails, there's no return statement found (since the return you provided was local only to the try block).
So as others have pointed out, you could either return something (e.g. -1) outside both the try and the catch blocks (but still inside the method),
or you could have a return statement in the catch block as well, so even if the try throws an exception, your method still returns a double.

Quadratic Formula in Java for Android, can't spot my mistake

I'm currently making an app for finding the roots of polynomials for android. At the moment I'm just dealing with quadratics however I can't spot my error. Whatever I've done it means my value for the root (only doing the first root right now), is always 0.0. Earlier I was trying to find my value for the discriminant and I kept getting the square of the 'b term' in the quadratic. My quadratic equation looks strange because of the way the application is set out, ever letter is shifted 1, so the closed form solution for quadratics in my app is -(c(+/-)(c^c-4*b*d)^(1/2))/(2*b). I would be grateful for any help, thanks! :)
P.S. Please try to ignore my awful code, I'm just trying to get it working at the moment :)
public void onButtonClick(View v)
{
double rx, ry, rz, disc, disc2, a, b, c, d;
String sa, sb, sc, sd, sx, sy, sz;
EditText ta = (EditText)findViewById(R.id.a_c);
EditText tb = (EditText)findViewById(R.id.b_c);
EditText tc = (EditText)findViewById(R.id.c_c);
EditText td = (EditText)findViewById(R.id.d_c);
EditText tx = (EditText)findViewById(R.id.x);
EditText ty = (EditText)findViewById(R.id.y);
EditText tz = (EditText)findViewById(R.id.z);
sa = ta.getText().toString();
sb = tb.getText().toString();
sc = tc.getText().toString();
sd = td.getText().toString();
sx = tx.getText().toString();
sy = ty.getText().toString();
sz = tz.getText().toString();
if(sa.matches("")) {a = 0;} else {a = Double.parseDouble(sa);}
if(sb.matches("")) {b = 0;} else {b = Double.parseDouble(sb);}
if(sc.matches("")) {c = 0;} else {c = Double.parseDouble(sc);}
if(sd.matches("")) {d = 0;} else {d = Double.parseDouble(sa);}
if(sx.matches("")) {rx = 0;} else {rx = Double.parseDouble(sx);}
if(sy.matches("")) {ry = 0;} else {ry = Double.parseDouble(sy);}
if(sz.matches("")) {rz = 0;} else {rz = Double.parseDouble(sz);}
disc2 = c*c-4*b*d;
if(a == 0) {rx = (-c+Math.sqrt(disc2))/(2*b); tx.setText(Double.toString(rx));}
}
Here's how I'd solve a quadratic equation. Sort this out first, then worry about getting data in and out:
/**
* Quadratic root finder
* #link http://stackoverflow.com/questions/23956437/quadratic-formula-in-java-for-android-cant-spot-my-mistake
*/
public class QuadraticRootFinder {
private static final double TOLERANCE = 1.0e-8;
public static void main(String[] args) {
if (args.length > 0) {
double a = Double.parseDouble(args[0]);
double b = ((args.length > 1) ? Double.parseDouble(args[1]) : 0.0);
double c = ((args.length > 2) ? Double.parseDouble(args[2]) : 0.0);
Complex [] roots = QuadraticRootFinder.getRoots(a, b, c);
for (Complex root : roots) {
System.out.println(root);
}
} else {
System.out.println("Usage: QuadraticRootFinder <a> <b> <c>");
}
}
public static Complex [] getRoots(double a, double b, double c) {
Complex [] roots = new Complex[2];
if (Math.abs(a) <= TOLERANCE) { // Linear equation; just one root
if (Math.abs(b) > TOLERANCE) {
roots = new Complex[1];
roots[0] = new Complex(-c/b);
} else {
throw new IllegalArgumentException(String.format("No roots possible for (a,b,c) = (%f10.3, %f10.3, %f10.3", a, b, c));
}
} else {
double discriminant = b*b-4.0*a*c;
if (discriminant > 0.0) { // Two real roots
roots[0] = new Complex(-b/2.0/a-Math.sqrt(discriminant)/2.0/a, 0.0);
roots[1] = new Complex(-b/2.0/a+Math.sqrt(discriminant)/2.0/a, 0.0);
} else { // Two complex conjugate roots
roots[0] = new Complex(-b/2.0/a, -Math.sqrt(-discriminant)/2.0/a);
roots[1] = new Complex(-b/2.0/a, +Math.sqrt(-discriminant)/2.0/a);
}
}
return roots;
}
}
class Complex {
private final double x;
private final double y;
Complex() {
this(0.0, 0.0);
}
Complex(double x) {
this(x, 0.0);
}
Complex(double x, double y) {
this.x = x;
this.y = y;
}
double getX() {
return x;
}
double getY() {
return y;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("(").append(x).append(",").append(y).append(")");
return builder.toString();
}
}

how to implement Java equivalent of Function Pointers via abstract classes

Im trying to to create a simple 4 function calculator using a jump table without switch case or if/else statements. I understand I can create the jump table via function pointers but I am kindda blanking out. I've started with the addition and subtraction part of the program but am trying to grasp the design/strategy to use. I am also getting an error when putting the method in the array, so far this is what i have:
public class Calculator {
public abstract class Functor{
abstract double Compute(double op1, double op2);
}
class Addition extends Functor
{
public double Compute(double op1, double op2){ return op1 + op2;}
}
class Subtraction extends Functor
{
public double Compute(double op1, double op2){ return op1 - op2;}
}
public static void main(String[] args) {
Functor add = new Addition(); // Problem here
Functor sub = new Subtraction(); // and here
}
}
any help or ideas for the step in the right direction is greatly appreciated!
thanks in advance!
Let's try this instead:
public enum Operation {
PLUS("+") {
double apply(double x, double y) { return x + y; }
},
MINUS("-") {
double apply(double x, double y) { return x - y; }
},
TIMES("*") {
double apply(double x, double y) { return x * y; }
},
DIVIDE("/") {
double apply(double x, double y) { return x / y; }
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
#Override public String toString() {
return symbol;
}
abstract double apply(double x, double y);
}
This will only work if you're using Java 5 or later, which has generics and enums. What this does is it gives you a static set of operations. You access them by typing Operation.PLUS or Operation.MINUS, etc.
To test it try this:
public static void main(String[] args) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
for (Operation op : Operation.values())
System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
}
For more information consult Effective Java, Second Edition by Joshua Bloch.
It's worth pointing out that Java has no notion of "function pointers". Rather you simple write an interface and write a class that implements that interface. The correct class to use is selected at runtime; hence, that is a "jump table" but it's hidden behind the semantics of object-oriented programming. This is known as polymorphism.
While that's decent (aside from not having constructors that work right) I'd do it different, using anonymous classes.
abstract class Functor {
public abstract double compute(double a, double b);
public static void main(String[] args) {
Functor add = new Functor() {
// defining it here is essentially how you do a function pointer
public double compute(double a, double b) { return a + b; }
};
Functor subtract = new Functor() {
public double compute(double a, double b) { return a - b; }
};
System.out.println(add.compute(1.0,2.0));
System.out.println(subtract.compute(1.0,2.0));
}
}
Result:
C:\Documents and Settings\glowcoder\My Documents>java Functor
3.0
-1.0
C:\Documents and Settings\glowcoder\My Documents>
You don't have any constructors to pass in any arguments to your sub-classes, I don't understand how you think opt1 and opt2 are going to be set without any constructors with those as parameters. This is not correct Java code right now.

Categories

Resources