How can we solve NaN conflict in java? - java

`java
//5. Write a program to read three sides of triangle and print area for valid data and to print “Invalid data”
// if either one side of the triangle is greater or equals to the sum of other two sides.
package com.company;
import java.util.Scanner;
import java.lang.Math;
public class EX_05 {
public static void main(String[] args) {
Scanner n = new Scanner(System.in);
System.out.println("Enter three sides of a triangle : ");
double a = n.nextDouble();
double b = n.nextDouble();
double c = n.nextDouble();
double s = (a+b+c)/2;
if((a>=(b+c)) || (b>=(a+c)) || (c>=(b+a)) ){
double area = Math.pow((s * (s - a) * (s - b) * (s - c)), 0.5);
System.out.println("The area of triangle is " + area + ".");
}
else {
System.out.println("Invalid data");
}
}
}
`
I wanted to conclude whether the sides of triangle is valid or not to calculate area of triangle.
Here is the output shown by IDE.

Looks like your condition is inverted. You always perform the calculation if the data is invalid and always print "invalid data" if the data is valid.
You should switch what you have in the else with what you have in the if.
Another option would be to add a ! in front of the entire condition.
Yet another would be to invert the logic of the entire condition.
Beyond that, the title of your question is completely unrelated to the actual problem. And please don't paste images of code. They hate that here on stack overflow. Its no fun re-typing all of someone's buggy code on your own machine just to help them find the problem. Post the code itself so it can be easily copied and tested.

Your condition, to check whether the sides form a valid triangle, is wrong. Please correct that and you should get a proper value for area.

Related

Extend below program for acute and obtuse angle triangle | using Sine cos functions

so I want to know how to make a program that will ask multiple questions and lead to multiple values or other questions to build on.
So I was building a "missing side of right triangle" program. Successful after a couple tries I wondered why not make the program solve obtuse or acute triangles. Well, I could program the law of sines and cosines. The problem is I don't know how. I learned the basics of java through 2-3 videos off youtube. I tried to make an if-else nested inside an if-else statement. But this is my code I tried to build upon:
import java.util.*;
import java.lang.Math;
public class MissingSide {
static java.util.Scanner userInput = new Scanner(System.in);
public static void main(String[] args){
int firstSideGiven = 0;
int hypotenuseGiven = 0;
Scanner userInput = new Scanner(System.in);
System.out.println("Are you trying to figure out a missing side given the hypotenuse and another side?");
System.out.println("Then this is the place :)");
System.out.print("What is the value of the first side, other than the hypotenuse?");
if (userInput.hasNextInt()) {
firstSideGiven = userInput.nextInt();
}else{
System.out.println("Give me somthing else to work with!");
}
System.out.println("What is your hypotenuse?");
if (userInput.hasNextInt()){
hypotenuseGiven = userInput.nextInt();
}else{
System.out.print("Wait, I want you to think about what you are doing with your life.");
}
System.out.println("Your missing side is: " + (Math.sqrt((Math.pow(hypotenuseGiven, 2)-Math.pow(firstSideGiven, 2)))));
}
}
And now I want to know what to do next, when I attempted to nest everything inside another if statement, it gave me an error I did not understand.
Well It would be great if you can share the problem and/or errors faced during the change.
Here is a basic logic to solve your issue -
You can use Math.cos and Math.sin functions to calculate function value.
These values can be used to calculate the missing side.
Note - Above functions accept value in radian, So change your degree value to radian before usage. i.e. -
double angleInDegree = 354;
double angleInRadian = Math.toRadians(angleInDegree);
double cos = Math.cos(angleInRadian);
Hope it helps. :)

Beginner's Java Code Help: Newton Raphson Square Root Loop

In my Java class for college we are learning about the Looping control structure, and we got an assignment to code a little program that I am guessing is supposed to give the square root of a number and keep on taking the square root until the difference or accuracy is met. Here are the instructions:
"Write a class called NewtonRaphson that can be used to find an approximate solution of sqrt(a) using Newton's method, for any positive real number.
Note: sqrt(a) can be expressed in functional notation as follows: f(x) = x2 – a,
From which f ' (x) = 2 * x,
Print the iteration sequence and the approximation for each iteration. (That is, in a tabular form).
Write a driver class called TestNewton. Use the following data to test the class NewtonRaphson.
• The initial guess is 5.0
• In this exercise, the process terminates when the difference between two consecutive approximations is less than 0.00005"
I have my code linked at the bottom here, the main class and the test class, but I am not getting the looping result I am just getting the same square root of 5 when I type in 5 after running the program. Can someone please tell me where I messed up on?
Thanks, I am really new to coding, and this took forever to make and I had to ask for some friends help.
Main Class: http://pastebin.com/eiUJFJjQ
Test Class: http://pastebin.com/sJ4dB5uZ
Or if you prefer the code here it is:
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class NewtonRaphson {
static final double DIFFERENCE = 0.00005;
double n;
double x;
double derivative;
double function;
double xold;
double xnew;
int i;
public NewtonRaphson(double n2, int x2)
{
n=n2;
x=x2;
function = Math.pow(n, 2)-x;
derivative = 2*n;
xnew=n-function/derivative;
xold=0;
}
boolean positive()
{
return (n >= 0);
}
public double findXNew(double xold2)
{
function = Math.pow(xold2, 2)-x;
derivative = 2*xold2;
return xold2-function/derivative;
}
public void findSqRtA()
{
i=0;
while(Math.abs(xnew-xold)> DIFFERENCE)
{
xold=xnew;
xnew=findXNew(xold);
i++;
System.out.println(this);
}
System.out.println("\nIteration completed, difference is less than 0.00005");
}
public String toString()
{
NumberFormat nf = NumberFormat.getInstance(); DecimalFormat df = (DecimalFormat)nf;
df.applyPattern("0.00000000");
return "The approximate value of the square root of "+x+" is " + xnew + "\n" +
"The number of iterations is " + i;
}
}
and
import java.io.Console;
import java.util.Scanner;
public class TestNewton {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number you would like to find the square root of");
int a = reader.nextInt();
NewtonRaphson nr = new NewtonRaphson(5.0, a);
nr.findSqRtA();
}
}
My output is this, but I want it to take the square root after each iteration's result.
Enter a number you would like to find the square root of
5
The approximate value of the square root of 5.0 is 2.3333333333333335
The number of iterations is 1
The approximate value of the square root of 5.0 is 2.238095238095238
The number of iterations is 2
The approximate value of the square root of 5.0 is 2.2360688956433634
The number of iterations is 3
The approximate value of the square root of 5.0 is 2.236067977499978
The number of iterations is 4
Iteration completed, difference is less than 0.00005
Newton-Raphson method is very interesting. You can use it to approximate real-valued function roots. x2 is only one of them. Check this fractals produced with Newton-Raphson method. So, do not underestimate Newton-Raphson.
Your code works. But your expectations are mistaken, you think that on every iteration you will update the guess. The code actually does it in the while loop.
You may do something like this, the epsilon may also be a parameter.
First, you give a large epsilon find a square root estimation.
Then input the last approximation with a slightly smaller epsilon, until you are satisfied with the result.
I think this is what you expect.
You can simplify the code. Check this code out.
Your code is actually producing the correct result for me. Therefore I'm not sure what the problem is.
For help with Newton's method you can refer to this article:
http://en.wikipedia.org/wiki/Newton's_method
Can you show us your output?
"I thought the program is supposed to take the square root of each new answer from the previous square root, it constantly takes the square root of 5. But I want it to take the square root of each iteration's result"
Oh, I see, that's because you have this:
NewtonRaphson nr = new NewtonRaphson(5.0, a);
Simply replace the 5.0 above with your previous number.

Analyzing the type of triangle using Java

The code below is supposed to analyze the type of a triangle based on the angles entered by the user in the terminal. However, in the first if statement although I set it to (a+b+c==d) - still, in the terminal if I enter 180, 1, 1 - instead of stopping the execution and printing Triangle is not possible., it instead says the triangle is isosceles. It's surely a mistake on my part. But I am a noob, so please correct my statements.
/**
* #date 20/4/2014
*/
import java.io.*;
public class Triangleanglederivation
{
public static void main (String args[])throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int a,b,c,d;
d=180;
System.out.println("Enter the three sides of the triangle:");
a=Integer.parseInt(in.readLine());
b=Integer.parseInt(in.readLine());
c=Integer.parseInt(in.readLine());
if(a+b+c==d)
System.out.println("Triangle is possible.");
if((a==b)&&(b==c)&&(c==a))
System.out.println("The triangle is equilateral.");
else if((a==b)||(b==c)||(c==a))
System.out.println("The triangle is isosceles.");
else if((a!=b)&&(b!=c)&&(c!=a))
System.out.println("The triangle is scalene.");
else
System.out.println("Triangle is not possible.");
}
}
Fix
if((a==b)&&(b==c)&&(c==a)&&(a+b+c==d))
System.out.println("The triangle is equilateral.");
else if(((a==b)||(b==c)||(c==a))&&(a+b+c==d))
System.out.println("The triangle is isosceles.");
else if((a!=b)&&(b!=c)&&(c!=a)&&(a+b+c==d))
System.out.println("The triangle is scalene.");
else
System.out.println("Triangle is not possible.");
Your checks for the triangle being equilateral, isosceles, and scalene are being applied regardless of whether the triangle is possible or not. You need to either add the possibility check (a+b+c==d) to each of those using && or nest the if/else such that they only happen when the if (a+b+c==d) has succeeded.

Arcsine does not change value for variable in Java

I've looked at various sites to try to solve my problem. I've also tried to look for any YT or other videos on trig in Java, but couldn't find anything. (I'm a noob, so I also don't always understand everything that most sites refer to).
Anyways, I'm trying to make a simple program to calculate parts of Snell's Law (I realize there are websites that do this). But arc-sine doesn't seem to affect my variable values at all
Here is the code:
import java.util.Scanner;
public class trig_functions_test {
public static void main(String[] args) {
Scanner HumanInput = new Scanner (System.in);
double n1, n2, Oi, OR;
System.out.println("Enter the first medium's index of refraction.");
n1 = HumanInput.nextDouble();
System.out.println("Enter the second medium's index of refraction.");
n2 = HumanInput.nextDouble();
System.out.println("Enter the angle of incidence.");
Oi = HumanInput.nextDouble();
System.out.println("Enter the angle of refraction.");
OR = HumanInput.nextDouble();
//if angle of refraction is the missing variable
if (OR == 0) {
Oi = Math.toRadians(Oi);
OR = (n1*Math.sin(Oi)/n2);
OR = Math.toRadians(OR);
OR = Math.asin (OR);
OR = Math.toDegrees(OR);
System.out.println(OR);
}
}
}
When I debug the program I get this:
First, here is the program in action:
(the 0 is just to signify no angle of refraction)
These are the results after the 2nd line in the if statement is evaluated(?):
After "OR" is converted to radians, the value of "OR" becomes 0.011364657670640462.
Then, and here is the problematic part, the part with the arc-sine is evaluated, and "OR" becomes 0.011364*90231927541* (the changed part is indicated between the *'s)
And then finally, "OR" is converted to degrees once more, and I am reverted back to my value after the second line (more or less) "OR," is then equal to 0.6511*609374816383* (again, the changed part is indicated between the *'s).
Your trouble stems from this line:
OR = Math.toRadians(OR);
You already have your answer in radians when you do this calculation:
OR = (n1*Math.sin(Oi)/n2);
When you convert it to radians again, you are skewing the result. Delete OR = Math.toRadians(OR); and your program will work as intended.
You're making your solution much more complicated than it needs to be. You should evaluate your expression in one shot by solving for the angle of refraction in Snell's law, like so:
Oi = Math.toRadians(Oi);
OR = Math.asin((n1/n2)*Math.sin(Oi));
OR = Math.toDegrees(OR)
System.out.println("Angle of refraction: "+OR);

Finding roots of quadratic equation using a specific class

i have this assignment that asks me to write a code that determines the roots of a quadratic equation (ax^2 + bx + c = 0). but i have to use the university's library (type.lib.Equation;).
i almost got everything figured out, except the case where there are two roots. i can get the 1st root but i'm still circling around to get the the 2nd root
my code so far
import java.util.Scanner;
import java.io.PrintStream;
import type.lib.Equation;
public class Check05A
{
/**
* #param args
*/
public static void main(String[] args)
{
PrintStream output = System.out;
Scanner input = new Scanner(System.in);
output.println("Enter a,b,c pressing ENTER after each... ");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
output.print("The equation: ");
Equation x = new Equation(a, b, c);
output.print(x);
int root = x.getRootCount();
if(root == 0)
{
output.println(" has no real roots.");
}
if(root == 1)
{
double r1 = x.getRoot(root);
output.println(" has the single root: " + r1);
}
if(root == 2)
{
double r1 = x.getRoot(root);
double r2 = -x.getRoot(root);
output.println(" has the two roots: " + r2 + " and " + r1);
}
if(root == -1)
{
output.println("\nis an identity - any value is a root.");
}
}
}
for example 1, 2, -4 should output as :
"has the two roots: -3.23606797749979 and 1.2360679774997898"
You're just putting negative sign to root 1.
This isn't always the case.
Look up the formula for finding the roots for a quadratic equation:
x=\frac{-b \pm \sqrt {b^2-4ac}}{2a}.
and inside your function x.getRoot(), return two values inside an array.
*Please note that this answer is for only TI-84 calculators using If statements to find the roots of any nth degree polynomial. If this does not answer the question for you, please move on.
I made a TI-84 program that is helpful to find the roots of any nth degree polynomial. Here is the code:
(note that Z and S were set to be the derivatives of f and g; you have to find these yourself (I will update this code later with a parameter where it will get f' and g' by itself. Set z and s to 1 to use it to find GCF or roots!) (Also, Y1 is found in vars, if you tab right after clicking vars button, pressing enter, then enter again)
To start, put the function/s that you are working with into Y1, Y2, etc...
enter code here :Prompt F,G`:Prompt Z:Prompt S:If Y1=F:If Y2=G:F*G=FS+GZ->H :If X≥Y:X-Y=I->I:Disp I:If I=0:If I>0:Repeat X-Y=J->J:Disp J
That's it! Super simple, but so helpful! Let me know of any improvements (I am going to make a derivative finder program soon to embed into this code soon!)
Thanks so much, and have fun with the code! -Evan

Categories

Resources