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);
Related
`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.
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. :)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have to Write a program in Java that will take the dimensions of two different homes and calculate the total square footage. The program will then compare the two values and print out a line of text appropriately stating whether it is larger or smaller than the other one.
I am not sure where to even begin. I am new to Java and have only done a Hello World
The first thing you have to do is take input from your user of the length and width of the object. Then you must calculate the sqr ft using the formula :
Length * Width = # of Sqr ft
If you want to do this to two houses you will just need to take two inputs for the second house of the length and width and display that homes total area the same way we did to the first house.
import java.util.*;
public class SqrFoot {
public static void main(String[] args) {
//creates a scanner object
Scanner scan = new Scanner(System.in);
//takes input
System.out.println("Enter the length : ");
double length = scan.nextDouble();
System.out.println("Enter the width : ");
double width = scan.nextDouble();
//calculates and displays answer
System.out.println(length*width + " Sqr ft");
}
}
Does this program take input from the user? If it does, you'll want to use a Scanner to accept user input, as such:
Scanner input = new Scanner(System.in);
You can then use the nextDouble() method to input the house dimensions, like so:
double length1 = input.nextDouble();
Then you can calculate the area of each house:
double area1 = length1 * width1;
Finally, you can use an if-else block to compare the two areas. Here's an example of how you could do it:
if (area1 > area2) {
System.out.println("House 1 is larger than house 2.");
} else if (area1 < area 2) {
System.out.println("House 1 is smaller than house 2.");
} else {
System.out.println("House 1 is the same size as house 2.");
}
This sounds like homework, so I'm not going to do it for you, but I will help you with syntax and let you put it all together.
To store a number you need to declare a variable. Variables come in all different types. There is a:
String Which like the name suggests, is a string of characters like "Hello World". To declare a String named hello that contains "Hello World", type the following:
String hello = "Hello World";
Some important things: String is capitalized. You will learn why later, but just remember it for now. The stuff you were storing in hello started with and ended with a ". As you will see, this is only the case for Strings. Finally, like you may already know, almost every line ends with a ;.
char Which is short for character and stores a single letter (or symbol, but worry about that later). To store the letter 'P' in a variable named aLetter, type the following:
char aLetter = 'P';
Some important things: char like the rest of the variable names I will tell you about, is lowercase. Also, a char starts and ends with an '. Next, I stored a capital P which in Java's mind is completely different than a lowercase p (the point I'm trying to make is everything in Java is case sensitive). Finally, even though my variable name aLetter is two words, I didn't put a space. When naming variables, no spaces. ever.
int Which is short for integer. An int stores a whole number (no decimal places) either positive or negative (The largest number an int can hold is around 2 billion but worry about that later). To store the number 1776 in an int named aNumber, type the following:
int aNumber = 1776;
Some important things: this is pretty straightforward, but notice there aren't any "'s or ''s. In Java "1776" is NOT the same as 1776. Finally, I hope you are noticing that you can name variables whatever you want as long as it isn't a reserved word (examples of reserved words are: int, String, char, etc.)
double Which is pretty similar to int, but you can have decimal points now. To store the number 3.14 in a double named aDecimal, type the following:
double aDecimal = 3.14;
boolean Which is a little harder to understand, but a boolean can only have 2 values: true or false. To make it easier to understand, you can change in your head (not in the code) true/false to yes/no. To store a boolean value of true in a variable named isItCorrect, type the following:
boolean isItCorrect = true;
There are tons more, but that is all you have to worry about for now. Now, lets go to math. Math in Java is pretty self explanatory; it is just like a calculator except times is * and divide is /. Another thing to make sure of, is that you are storing the answer somewhere. If you type 5-6; Java will subtract 6 from 5, but the answer wont be saved anywhere. Instead, do the following:
int answer = 0;
answer = 5-6;
Now, the result (-1) will be saved in the int named answer so you can use it later.
Finally, we have decision making. In computer science, you change sentences like "If the person's age is at least 21, let them into the bar. otherwise, don't let them in." In decision making, you need to turn all of your questions into yes/no questions. When you need to decide a yes/no question, use what are called if statements. The way to write if statements are a little weird: you write the word if then you ask your question in parentheses and you don't but a ;. Instead you put a set of curly braces {}, inside which you write your code that will run if the question in the if statement is true. For example, the bar example above would be, in code, the following:
int age = 25;
boolean letHimIn = false;
if(age>=21)
{
letHimIn = true;
}
Now, the question is, how do you ask a question. To do so, you use the following: <,>,<=,>=,==,!=. These are called comparators because they the things on either side of them. They do the following: < checks if the number on the left is less than the number on the right, > checks if the number on the left is greater than the number on the right, <= checks less than or equal, >= checks greater or equal, == checks if the two numbers are equal, and != checks if the two numbers are not equal. So if(age>=21) asks the question, is the number stored in age greater or equal to 21? If so, do the code in curly braces below. If not, then skip the code. As one more example, the code checks if age is exactly equal to 21 and if so, set letHimInTheBar to true.
int age = 25;
boolean letHimInTheBar = false;
if(age==21)
{
letHimInTheBar = true;
}
Since age is equal to 25 not 21, the code to make letHimInTheBar true never ran which means letHimInTheBar. The final thing to know about decisions is you can use a boolean variable to ask a question directly. In the following example, we are only letting people whose age is NOT equal to 30 into the bar and if we let them into the bar we will print "Welcome to the bar." and if we didn't then we will print "Stay away.". As a reminder ! in Java means not. Meaning that it will flip true to false and false to true.
int age = 25;
int badAge = 30;
boolean letHimIn = false;
if(age!=badAge)
{
letHimIn = true;
}
if(letHimIn)
{
System.out.println("Welcome to the bar.");
}
if(!letHimIn)
{
System.out.println("Stay away.");
}
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.
I am trying to make a calculator for college gpa's. I cut out all like 20 if statements that just say what each letter grade is. I fixed my first program for anybody looking at this again. The program now works, but regardless of the letters i type in the gpa it returns is a 2.0 . If anybody sees anything wrong it would be very much appreciated...again. Thanks
import java.util.Scanner;
public class universityGPA {
public static void main(String args[]){
int classes = 4;
int units[] = {3, 2, 4, 4};
double[] grade = new double[4];
double[] value= new double[4];
int counter = 0;
double total = 0;
double gpa;
String letter;
while(classes > counter){
Scanner gradeObject = new Scanner(System.in);
letter = gradeObject.next();
if(letter.equalsIgnoreCase("A+") || letter.equalsIgnoreCase("A")){
grade[counter] = 4;
}
if(letter.equalsIgnoreCase("F")){
grade[counter] = 0;
}
value[counter] = grade[counter] * units[counter];
counter++;
}
for(int i = 0; i < classes; i++ ){
total += value[i];
}
gpa = total/classes;
System.out.println("You gpa is " +gpa);
}
}
You forgot to initialize grade. The NullPointerException is telling you that grade is null. The exception is thrown the first time you try to use grade, in the statment grade[counter] = 4;. Allocate as much space as you need with new.
Initialization of grade can be done statically as well dynamically:
double []grade = new double[4];
or
double []grade = new double[classes];
Do the same for value as well.
Here are a few pointers for cleaning up your code:
Try to be more consistent with your formatting. Make sure everything is properly indented and that you don't have lingering spaces at the beginnings or endings of lines (line 18).
You should declare variables as close to the first spot you use them as possible. This, along with making your code much more readable, minimizes the scope. For instance, on line 18, you initialize letter, but it is never used outside the scope of the while statement. You should declare the variable right there, along with the initializer (String letter = gradeObject.next()).
Declaring arrays in the type name[] form is discouraged. It is recommended to use the type[] name form instead.
Try to separate your program into distinguished sections. For instance, for this program, you can clearly see a few steps are involved. Namely, you first must grab some input, then parse it, then calculate the return value. These sections can be factored out into separate methods to clean up the code and promote reuse. While it may not seem to yield many benefits for such a simple program, once you start working on larger problems this organization will be absolutely mandatory.
NullPointerException means you are trying to access something that does not exist.
Since your grade[] is null, accessing it on line 21 by grade[counter] actually means you are accessing something that has yet to be created.
You need to initialize the array, so it actually has an instance.