This is the value of the double "m" in my program (the mass of a planet after calculations, this value is specifically for the mass of Earth)
5.973405437304745E24
When printing using System.out.println(m);
The output is
5.973405437304745E24 (correct output)
When printing using System.out.println(Math.round(m));
The output is
9223372036854775807 (incorrect output)
How am I able to shorten the value of m so it fits within %6s?
Like this for example
5.97E24
This is my code below. The assignment requires us to output the final values in a formatted chart (as I've attempted to do below)
//Java imports
import java.util.*;
import java.lang.Math;
//Main class
class Main {
public static void main(String[] args) {
//Initializing scanner name userInput
Scanner userInput = new Scanner (System.in);
//Greeting statement, prompts user to input the circumference in km
System.out.println("\nWelcome to the Escape Velocity Application. To begin, please enter the following information below. \nEnter the circumference (km):");
//Stores circumference in double named "circum" and converts the value to its meter equivalent (unit conversion required)
double circum = userInput.nextDouble() * Math.pow(10, 3);
//Prompts user to input the acceleration in m/s^2
System.out.println("Enter the acceleration due to gravity (m/s^2):");
//Stored value in double named "f"
double f = userInput.nextDouble();
//Gravitational Constant
double G = 6.67408e-11;
//1 - Radius calculation using the circumference of a circle formula
double r = circum/(2*Math.PI);
//2 - Mass calculation using the gravity formula
double m = f*Math.pow(r, 2)/G;
//3 - Calculation escape velocity using the escape velocity formula
double e = (Math.sqrt((2.0*G*(m))/r));
//Final output statements
System.out.println("\nThe radius is: " + Math.round(r * Math.pow(10, -3)) + " kilometers.");
System.out.println("The mass is: " + m + " kg.");
System.out.println("The escape velocity is: " + Math.round(e) + " m/s.");
//Formatted output statements
System.out.format("\n%20s %6s %10s", "Radius:", Math.round(r * Math.pow(10, -3)), "km.");
System.out.format("\n%20s %6s %10s", "Mass:", Math.round(m), "kg.");
System.out.format("\n%20s %6s %10s", "Escape Velocity:", Math.round(e), "m/s.");
}
}
This is what the output looks like. The center of the second line is offset due to the long value of m.
The radius is: 6378 kilometers.
The mass is: 5.973405437304745E24 kg.
The escape velocity is: 11181 m/s.
Radius: 6378 km.
Mass: 9223372036854775807 kg.
Escape Velocity: 11181 m/s.
You could use the following code:
double x = 5.973405437304745e24;
System.out.printf("Mass: %.2e kg.%n", x);
Which outputs Mass: 5.97e+24 kg..
%.2e formats the number and %n just adds a newline character. The .2 specifies that two decimal places after the dot are desired. The e requests scientific notation from the formatter.
The problem with Math.round() is, that the result is stored in a long which cannot represent such a large number.
Related
I declared a double variable as below:
double x=56.27d
And then all I tried to do is the following: (56.27*10*10)
System.out.println(xE2);
And this is not working.
There isn't an 'E' operator in java. This would conflict with variable names for one thing. double xE2=x*1e2; In this case, xE2 is a variable name, but I do use 1e2 as a java literal.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
double d = sc.nextDouble(); // Get input from the user
System.out.println(d * 10 * 10);
// Displaying it using scientific notation
// Format the number rounded up to two places after decimal and into scientific notation
System.out.println(String.format("%.2e", d * 10 * 10));
// Examples of e or E with double literals
double x = 1e2; // 1 * 10 to the power of 2 = 100.0
System.out.println(x);
double y = 1E2; // 1 * 10 to the power of 2 = 100.0
System.out.println(y);
double z = 1e+02; // 1 * 10 to the power of 2 = 100.0
System.out.println(z);
System.out.println(d * 1e2);// i.e. d * 100.0
}
}
A sample run:
Enter a number: 56.27
5627.0
5.63e+03
100.0
100.0
100.0
5627.0
Notes:
Check this to learn more about Formatter.
E or e can be used only with double literals, not double variables.
Feel free to comment in case of any doubt/issue.
You shouldn't use the exponent notation since it is a part of double literal. Try multiplying.
System.out.println(x * 10 * 10)
I suggest you to read java.util.Math library documentation, it includes many scientific functions like Exponents: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
This are other problems I ran into that is having the same issue. Can anyone point out my logic error in the following below:
Question: A regular polygon is an n-sided polygon in which all sides are of the same length and all angles have the same degree... (Exercise 4.5)
This was my response:
import java.util.Scanner;
public class Exercise04_05 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of sides: ");
double n = input.nextDouble();
System.out.print("Enter the side: ");
double s = input.nextDouble();
double area = n * Math.pow(s, 2) / 4 * Math.tan(Math.PI / n );
System.out.println("The area of the polygon is " + area);
}
}
Please explain where the Logic error is. i commented out the code or else I'll keep getting errors preventing me from submitting the question.
Your formula is wrong and it contains an error.
First / 4 is an integer division which is rounded to an int, so you get mostly an error. You have to use / 4.0 so you get the right division.
The formula for calculation the area of a polygon is
A = 1 / 4 * n * s2 * cot(PI / n)
Note it is cotangens, not tangens. As java.math has no cotangens you have to calculate it by yourself, e.g. 1 / Math.tan(x).
So finally this should work for you:
double area = n / 4.0 * Math.pow(s, 2) / Math.tan(Math.PI / n );
I'm writing a program that will calculate the BMI of a person. Here's the assignment that I was given:
"Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. Write a program that prompts the user to enter a weight W in pounds and height H in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters."
Input: (Line 1) Real number within 50 to 200
(Line 2) Real number within 10 to 100
Output: BMI value (Floating point should only be printed until the second decimal point)
The problem is that whenever I use "System.out.printf("%.2f\n", BMI)", the output is rounded up rather than cutting off the rest of the decimal point. Here's my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double weight = input.nextDouble();
double height = input.nextDouble();
double weightKG;
double heightM;
double heightMSquare;
double BMI;
final double kilogram = 0.45359237;
final double meter = 0.0254;
while ((weight > 200) || (weight < 50)) // Error catching code.
{
weight = input.nextDouble();
}
while ((height > 100) || (height < 10))
{
height = input.nextDouble();
}
weightKG = weight * kilogram; // Convert pounds and inches to
kilograms and meters.
heightM = height * meter;
heightMSquare = Math.pow(heightM, 2); // Compute square of height in
meters.
BMI = weightKG / heightMSquare; // Calculate BMI by dividing weight
by height.
System.out.printf("%.2f\n", BMI);
}
}
Here is a method I wrote that solves this with regexes and string manipulation.
private static String format2Dp(double x) {
String d = Double.toString(x);
Matcher m = Pattern.compile("\\.(\\d+)").matcher(d);
if (!m.find()) {
return d;
}
String decimalPart = m.group(1);
if (decimalPart.length() == 1) {
return d.replaceAll("\\.(\\d+)", "." + decimalPart + "0");
}
return d.replaceAll("\\.(\\d+)", "." + decimalPart.substring(0, 2));
}
What I did was turning the double to a string, extract the decimal part out of it and substringing the decimal part. If the decimal part is only 1 character long, add a zero to the end.
This method works with numbers expressed in scientific notation as well.
Here's the exercise:
35. Write a Java program to compute the area of a polygon. Go to the editor
Area of a polygon = (n*s^2)/(4*tan(π/n))
where n is n-sided polygon and s is the length of a side
Input Data:
Input the number of sides on the polygon: 7
Input the length of one of the sides: 6
Expected Output
The area is: 130.82084798405722
My code returns 127.30573435631248 (length = 7, sides = 6)
The code on the website returns 130.82084798405722 (length = 7, sides = 6)
I'm having trouble seeing why mine is different from theirs...
Any ideas?
Here's my code:
public static void exercise35(){
int number1 = integerInput(); //set to 7, length
int sides = integerInput(); //set to 6, sides
double area = (sides * (number1 * number1)) / (4.0 * Math.tan((Math.PI / sides)));
System.out.println("The area of a polygon with " + sides + " sides of length " + number1 + " = " + area);
}
Here's the solution from http://www.w3resource.com/java-exercises/basic/index.php (exercise #35)
import java.util.Scanner;
public class Exercise35 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input the number of sides on the polygon: ");
int ns = input.nextInt();
System.out.print("Input the length of one of the sides: ");
double side = input.nextDouble();
System.out.print("The area is: " + polygonArea(ns, side)+"\n");
}
public static double polygonArea(int ns, double side) {
return (ns * (side * side)) / (4.0 * Math.tan((Math.PI / ns)));
}
}
You mixed sides and number in the formula.
That teaches an interesting lesson of programming: "Give sensible names to variables".
Change 6 and 7 and you'll get the answer you want : ) And in the future, please try debugging your code first to see what's going on.
Exercise 2.12
(Compute arithmetic progression) An arithmetic progression(AP) or arithmetic sequence is a sequence of numbers such that the difference between the consecutive terms is constant. For instance the sequence 5,7,9,11,13,15... is an AP with a common difference of 2. If the initial term of an AP is A1 and the common difference of successive members is d, then the nth term of the sequence an is given by:
a n = a 1 + (n-1)*d
Write a program that prompts the user to enter a 1 and d and computes a 46.
Enter speed and acceleration: 60 3.5
The minimum runway length for this airplane is 514.286
This is my code:
import java.util.Scanner;
public class Chapter2Exercise12 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter speed: ");
double speed = input.nextDouble();
System.out.print("Enter acceleration: ");
double acceleration = input.nextDouble();
double length = speed + (46 - 1)* acceleration;
System.out.println("The minimum runway length for this airplane is " +
length + " meters");
}
}
This is the answer from the book:
import java.util.Scanner;
public class Exercise02_12 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter speed v: ");
double v = input.nextDouble();
System.out.print("Enter acceleration a: ");
double a = input.nextDouble();
double length = v * v / (2 * a);
System.out.println("The minimum runway length for this airplane is " +
length + " meters");
}
}
Does anyone understand how they get the formula from length?
It can be relevant to other people who don't understand this and need to apply this in a project.
It appears that your code is computing A46 term correctly.
But, the question was they were actually asking is missing something like that:
"An airplane starts its liftoff in velocity 0.
Ask the user to type in the airplane's acceleration and liftoff speed (minimal speed needed for liftoff).
Compute the minimal length needed for the runway."
The answer, of course, is by using the formulas previously mentioned in the comments.