Beginner, basic trig table in increments of 5 degrees - java

For a class that I am taking I am trying to create a program that produces a table of sin(), cos(), and tan() values for angles from 0 to 180 degrees in steps of 5 degrees.
!http://i65.tinypic.com/14ahliq.jpg
So far I have the following code, which produces an introduction and the first two lines of the table, but I cannot figure out how to get it to repeat.
import java.util.*;
public class Angles {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("This program computes the");
System.out.println("sin(), cos(), and tan() values");
System.out.println("for angles from 0 to 180 degrees");
System.out.println("in steps of 5 degrees.");
System.out.println("");
System.out.println("Angle\tSin()\tCos()\tTan()");
double Anglex = 0;
for(double i = 5;i <= Anglex;i += 5) {
Anglex = 0 + i;
}
double Sinx = Math.sin(Math.toRadians(Anglex));
double Cosx = Math.cos(Math.toRadians(Anglex));
double Tanx = Math.tan(Math.toRadians(Anglex));
System.out.println(Anglex + "\t" + Sinx + "\t" + Cosx + "\t" + Tanx);
}
}

Is not really ok that you ask people on forums to solve your assignments.
Otherwise, several issues with your little program (didn't test, please do it yourself).
anglex should start at 0 and stop at 180. So for(int anglex=0; anglex<=180; anglex+=5). Use anglex instead of i, inside the loop.
the calculations for sinx, cosx, tanx and the printing of the new line should be inside the curlies {}. As your code is right now, the only thing inside the loop is the increment of anglex.
Sorry for not providing the full solution, pretty sure you can do it.

Recast your for loop to
for (double Anglex = 0; Anglex <= 180; Anglex += 5){
Note well the opening brace to enclose multiple subsequent statements. Don't forget to balance it with a closing }; probably after the println call.
Using a double as a loop index is not to everyone's taste (you can get yourself into trouble if you are not using whole numbers), but this is fine in this instance, particularly also as you are using <= as the stopping condition.
Starting variable names with an upper case letter is also to be discouraged in Java as it's unconventional.

Your for loop only applies on the Anglex = 0+i line.
Add {} to the whole section that should be repeated.

public static void main(String[] args) {
System.out.println("This program computes the");
System.out.println("sin(), cos(), and tan() values");
System.out.println("for angles from 0 to 180 degrees");
System.out.println("in steps of 5 degrees.");
System.out.println("");
System.out.println("Angle\tSin()\tCos()\tTan()");
double maxAngleX = 180.0;
for (double angleX = 5; angleX <= maxAngleX; angleX += 5) {
double Sinx = Math.sin(Math.toRadians(angleX));
double Cosx = Math.cos(Math.toRadians(angleX));
double Tanx = Math.tan(Math.toRadians(angleX));
System.out.println(angleX + "\t" + Sinx + "\t" + Cosx + "\t" + Tanx);
}
}

for(double i = 5;i <= Anglex;i += 5) {
Anglex = 0 + i;
double Sinx = Math.sin(Math.toRadians(Anglex));
double Cosx = Math.cos(Math.toRadians(Anglex));
double Tanx = Math.tan(Math.toRadians(Anglex));
}
Enclose the above statements inside a { and }. The for loop applies for only the first statement in your code.

Related

How do I break a loop without the if-condition in the results

import java.util.Scanner;
public class Tykinkuula {
public static void main(String[] args) {
Scanner lukija = new Scanner(System.in);
double highest = 0;
int seconds = 0;
double height = 0;
System.out.println("Syötä tykinkuulan lähtönopeus: ");
double startspeed = Double.parseDouble(lukija.nextLine());
System.out.println("Syötä painovoima: ");
double gravity = Double.parseDouble(lukija.nextLine());
System.out.println(seconds + "\t" + height + "\t" + startspeed);
while (true) {
if (height < 0.0) {
break;
}
height = height + startspeed;
seconds = seconds + 1;
startspeed = startspeed - gravity;
if (height > highest) {
highest = height;
}
System.out.println(seconds + "\t" + height + "\t" + startspeed);
}
System.out.println("");
System.out.println("Tykinkuulan suurin korkeus oli " + highest);
}
This is a code for a calculator that gives me the speed and height of a canonball every second. You input a desired starting speed and gravity, and then run the code.
When I run this code, it gives me 3 columns, seconds, height and speed.
The loop is supposed to end before the canonball hits the ground, so basically before height = 0. But when I run the code it gives me a negative height, but I need the program to only show results of when the ball is in the air.
So, how do I remove the negative result?
Simply move
if (height < 0.0) {
break;
}
after the calculation. Since you only check once it is below 0, you need to check after calculating the next step. Currently you check at the start of the loop, where height still has the value from the previous iteration (0), while the next calculation outputs a negative number

Changing `double` output inside for loop

I want to start off saying that I'm new at this. I'm trying to make a for loop that will Show me the different 40 yard dash times converted into MPH. The problem is output that's being shown:
5.96 40 Time is 13.727882855399633 Miles Per Hour
6.96 40 Time is 11.755485893416928 Miles Per Hour
7.96 40 Time is 10.27866605756053 Miles Per Hour
I want it to show as 5.96, 5.97, 5.98, etc instead of 5.96 and 6.96.
Does anyone understand what I'm trying to do as well as to fix this problem I'm having?
public class FortyToMPH {
public static void main (String args []) {
double yards, foot, FeetInMiles, SecondsPerHour,FeetLength;
double FortyTime, Minutes, SecondsPerMile, MPH;
int counter;
counter = 0;
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime++) {
yards = 40; // length in yards
foot = yards * 3; // convert to feet
System.out.println();
FeetInMiles = 5280; // The number of feet in a Mile
SecondsPerHour = 3600;
FeetLength = FeetInMiles / foot; // You divide the Feet in Miles by the feet conversion of 40 yards
System.out.println();
SecondsPerMile = FeetLength * FortyTime;
MPH = SecondsPerHour / SecondsPerMile;
System.out.println(FortyTime + " 40 Time is " + MPH + " Miles Per Hour ");
counter++;
// every 10th line, print a blank line
if(counter == 10) {
System.out.println();
counter = 0; // reset the line counter
}
}
}
}
The problem is that you're using the ++ operator in your for loop definition:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime++) {
Change the for loop to a while loop that includes a line incrementing FortyTime by 0.01 each loop:
while(FortyTime <= 7.99) {
FortyTime += 0.01;
// execute the rest of your code here
}
MarounMaroun rightfully pointed out that using a double as a loop counter runs the risk of nasty floating-point arithmetic errors, so I've changed the for loop to a while loop.
The ++ operator means "reassign the value of x as x + 1." It'll only give you increments (or decrements, with --) of 1.
Note that this is going to print out hundreds of lines before it completes.
I would recommend you to use int in your loop and perform all calculations of doubles inside the loop to prevent problems with floating point arithmetic:
for(int i = 0; i < something; i++) {
double fortyTime = 4.96 + i;
//...
}
Also please pay attention to Java Naming Conventions and rename your variables.
To demonstrate problems of floating point arithmetic, try this loop:
for(double i = 0; i < 1.0; i += 0.1)
System.out.println(i);
This will print
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
And you don't want output like this in your program.
Here I modified the code you gave to print doubles as a two decimal place numbers (see format %.2f) produced in the loop while (the step for the loop is defined in DELTA variable).
public class FortyToMPH
{
public static void main (String args [])
{
double yards, foot, feetLength;
double fortyTime = 4.96, minutes, secondsPerMile, mph;
int counter = 0;
/**
* Constants.
*/
final double FEET_IN_MILES = 5280;
final double SECONDS_PER_HOUR = 3600;
final double DELTA = 0.01;
final double END = 7.99;
while (fortyTime <= END)
{
yards = 40; // length in yards
foot = yards * 3; // convert to feet
feetLength = FEET_IN_MILES / foot; // You divide the Feet in Miles by the feet conversion of 40 yards
secondsPerMile = feetLength * fortyTime;
mph = SECONDS_PER_HOUR / secondsPerMile;
System.out.format("%.2f 40 Time is %.2f Miles Per Hour%n", fortyTime, mph);
counter++;
// every 10th line, print a blank line
if(counter == 10) {
System.out.println();
counter = 0; // reset the line counter
}
fortyTime += DELTA;
}
}
}
just change the for loop like this:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime=FortyTime+.01)
and print it like
System.out.println((float)FortyTime + " 40 Time is " + MPH + " Miles Per Hour ");
You need to make two changes:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime=FortyTime+0.01)
So that the FortyTime is incremented by 0.01 and not 1 and
System.out.printf("%.2f 40 Time is %f Miles Per Hour ", FortyTime, MPH);
So that it prints in correct precision.

Problems with dividing while using for loop

For some reason whenever I try to run this code, speed remains at 0 and it counts i up to x and then speed is suddenly changed to 1.0. speed is supposed to be a decimal of x depending on how many times the for-loop has run through. I don't understand why this is happening and would be very grateful for some clarity.
double speed;
int x = 200;
for(int i = 0; i <= x; i++){
speed = i/x;
System.out.println("Speed- " + speed);
System.out.println("Ticks- " + i);
}
for(int i = x; i >= 0; i--){
speed = i/x;
System.out.println("Speed- " + speed);
System.out.println("Ticks- " + i);
}
Try this:
double x = 200; // use a double instead of an int
The problem? you were dividing two ints, and the result is another int. By converting one of the two operands to a double, the division will now yield a number with decimals.
x must be an float variable in order to get the correct result. If both, i and x are integers, speed is an integer too, and that's the reason you get only 0 and 1

String not printing out after conclusion of loop

So after browsing the already asked questions on here and other sites I figured I would give this a go.
I am working on an exercise that wants you to set up a program in Java that takes an input of 10 numbers and computes the average(mean) and the standard deviation and outputs them.
My problem is that when I run the program, and then enter my desired 10 values and hit enter, nothing happens. For some reason the System printouts that occur after the loop are not being executed. The println inside the loop is not necessary, but is just to show that the values are being calculated correctly as the loop runs, and they are.
I am aiming to have the current value that myValues is assigned to to be added to sum1, and the square of myValues to be added to the sqrdSum. sqrdSum is just a variable I made to sum the squares of the values entered so that the calculation of standard deviation later in the program will be cleaner.
As expected, I am not looking for this to be done for me, just some advice on how to adjust my code such that the printlns at that occur after the loop will execute. I am expecting it to be something to do with my logic, but can not figure it out. Hopefully it is something simple I have managed to miss.
Thanks.
So far I have set it up using a for loop:
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = input1.nextDouble();
for (int count = 0; count <= n; count++) {
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
myValues = input1.nextDouble();
}
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794
The problem is, that input1.nextDouble() blocks until the next number is entered. You are entering 10 numbers, but you expect 11 inputs, since you have this line
double myValues = input1.nextDouble();
which executes once and
myValues = input1.nextDouble();
inside the loop which executes 11 times. Just move it at the beginning of the loop:
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0;
for (int count = 0; count < n; count++) {
double myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
As Brian noted, you also have an off-by-one error. You start at 0 but count to 10, that makes 11 loop cycles. Change <= to <
Just change count <= n to count < n in your cycle. You're accidentaly expecting one too many values.
While the answers given did solve your original problem there is also another problem with your code. You won't be getting the correct mean because of how you initiate it and then don't set it to any values after your for loop.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
The lines above should read,
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
and then after your for loop you should calculate mean1 and std1 like the code below.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0.0;
for (int count = 0; count < n; count++) {
myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
mean1 = sum1 / n;
std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794

How can I trap a particular value of the counter in the for loop

How can I trap a particular value of the counter in the for loop, for which I get the maximum calculated value ..for example:
import com.imonPhysics.projectile2;
public class motion2{
public static void main(String[] args){
double range=0,v=35,maxrange=0,angle=0;
int x=0;
projectile2 p1=new projectile2();
System.out.println("the given velocity is: 20 m/s \n" );
System.out.println("The value of g is: 9.8 m/s^2\n\n" );
for(int j=0;j<=90;j+=5){
x=j;
range=p1.calculate(v,j);
System.out.println("For the angle :" + j+" the range is: " + range);
if(range > maxrange)maxrange=range;
}
System.out.println(" the maximum range is :"+ maxrange);
System.out.println(" the angle at which the range is max is : " + angle);
}
}
how can I trap the angle for maxrange.
If I understand your question correctly, you can use exactly the same approach you are using to determine maxrange:
for (...) {
...
if (range > maxrange) {
maxrange = range;
angle = j; // <--
}
}
Maybe I don't understand the problem correctly, but do you if you want the angle with that the max range is reached, then just do angle = j inside the if.

Categories

Resources