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
Related
This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 3 years ago.
import java.text.NumberFormat;
public class Mortgage {
public static void main(String[] args) {
int p = 1000000;
NumberFormat percent = NumberFormat.getPercentInstance();
double r = Double.parseDouble(percent.format(3.92*12));
int t = (int)(r);
double n;
n = Math.pow(30,12);
int f = (int) Math.floor(n);
int a =(1+t)^f;
int b = (a-1);
int c = (t*a)/b;
int m = p*c;
NumberFormat currency = NumberFormat.getCurrencyInstance();
String result = currency.format(m);
System.out.println(result);
}
}
I have tried to changed r to int but I still got exception. What am I not writing correctly?
You use NumberFormat.getPercentInstance() to format your number. This adds a % symbol and other number formatting (depending on your default locale). Then the Double.parseDouble(...) call fails because the number is not a pure double number.
There is no need to format and parse the number, you can just assign it directly to the double variable as it is a constant anyways.
I see several problems.
double n;
n = Math.pow(30,12);
int f = (int) Math.floor(n);
30 to the 12th power. That does not make sense for a 30 year mortgage Did you mean 30*12 for 360 pay periods. Or possibly Math.pow(30,1+montlyRate) where monthlyRate = (AR/100)/12 and AR = annual rate).
int a =(1+t)^f;
The operator ^ is not power but an exclusive OR. You probably didn't want that either.
I recommend you check out this Wiki entry on computing Mortage Payments
Here is one way to do calculate it and then display it per month.
double in = 5.5; // annual percentage rate
double mo_rate = (in / 100) / 12.; // monthly rate
double PV = 400_000.; // present value (cost of the house).
double f = Math.pow(1 + mo_rate, 360); // factor resulting from the linear
// expansion
double payment = mo_rate * PV * f / (f - 1); // Monthly payment including
// interest and
// principal
System.out.printf("Monthly payment is %7.2f%n", payment);
Note: different banks and/or countries may do it differently.
The answer is in the exception java.lang.NumberFormatException: For input string: "4,704%"
percent.format(3.92*12) returns the String : 4 704 % and this can't be parsed to double, because of the space and the % symbol, you just need to multiply it by 100 to consider it as a percentage
double r = 3.92 * 12 * 100;
As you're using only ints you fall into the int division problem and you'll get a 0 at the end, so you may use at leat one double ot cast one durint the division
int a = (1 + t) ^ f;
double b = (a - 1);
double c = (t * a) / b;
double m = p * c;
// OR
int a = (1 + t) ^ f;
int b = (a - 1);
double c = (t * a) / (double) b;
double m = p * c;
Also ^ is thr XOR symbol, to use power computation :
double a = Math.pow(1+t, f);
For the result, it depends on r:
double r = 3.92 * 12 * 100; gives -10 308,38 €
double r = 3.92 * 12; gives 999 998,95 €
And use names that explain what the variable is, as much as possible
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.
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 );
This question already has answers here:
How to merge two int(s) into a double in JAVA?
(6 answers)
Closed 6 years ago.
Is there a way to force a number to be placed behind the decimal mark of a number?
Say I have a number = 2, and another number = 23. Is there a way for me to force 23 into 0.23, so that when I add the numbers I end up with 2.23? And is there a way to do this when the number of digits in the second number, in this case 23, are unknown?
EDIT:
I realize this was badly written. I am currently working on a program that converts from imperial units to metric units. Part of the code looks like this:
double feet = nextDouble();
double inches = nextDouble();
double heightInMeters = (feet + (inches/10)) / 3.2808;
The problem with this code is that I anticipate that the user only enters a value <0, 9> for feet. Is there a way to force the input for inches to something like 0.x where x = inches so that it doesn't matter if the number is greater than 9?
Would be lovely if it was possible without using toString() and parseInt().
You can get the number of digits in an integer, i, using:
1 + Math.floor(Math.log10(i))
(not ceil(log10(i)), since that calculates that 1 has zero digits)
You then need to divide i by 10 to the power of that number:
i / Math.pow(10, 1 + Math.floor(Math.log10(i)))
e.g.
23 / Math.pow(10, 1 + Math.floor(Math.log10(23))) == 0.23
Ideone demo
Alternatively, if you think those floating point operations log and pow are too expensive, you can determine the number of digits with a loop:
int d = 1;
while (d < i) d *= 10;
then
System.out.println(i / (double) d);
(noting that you need to cast at least one of the numerator or denominator to a floating point type, otherwise it will use integer division).
Try parsing to double like this, from a string:
Option 1
try
{
int n = 2;
int decimal = 23;
String full = Integer.toString(n) + '.' + Integer.toString(decimal);
double val = Double.parseDouble(full);
} catch (Exception e) //Or whatever exception
{
//Code
}
Option 2
Of course, there are simpler methods, like this:
try
{
int n = 2;
int decimal = 23;
double val = Double.parseDouble(n + "." + decimal);
} catch (Exception e) //Or whatever exception
{
//Code
}
I personally would recommend the solution directly above, since it is the simplest, and requires the least code.
Live Example for Second Option
Simple implementation using Strings:
public class Mainclass {
public static void main(String[] args) {
Integer num = 1546;
Integer num2 = 2;
String s = num.toString();
s = "0." + s;
Double d = Double.parseDouble(s);
System.out.println(num2+d ); // 2.1546
}
}
I have to convert a temperature in degrees Celsius to Fahrenheit. However when I print the temperature in Celsius I get the wrong answer ! Please help ! (The formula is c = (5/9) * (f -32). When I type in 1 for degrees farenheit I get c = -0.0. I have no idea what is wrong :s
Here is the code
import java.io.*; // import/output class
public class FtoC { // Calculates the temperature in Celcius
public static void main (String[]args) //The main class
{
InputStreamReader isr = new InputStreamReader(System.in); // Gets user input
BufferedReader br = new BufferedReader(isr); // manipulates user input
String input = ""; // Holds the user input
double f = 0; // Holds the degrees in Fahrenheit
double c = 0; // Holds the degrees in Celcius
System.out.println("This program will convert the temperature from degrees Celcius to Fahrenheit.");
System.out.println("Please enter the temperature in Fahrenheit: ");
try {
input = br.readLine(); // Gets the users input
f = Double.parseDouble(input); // Converts input to a number
}
catch (IOException ex)
{
ex.printStackTrace();
}
c = ((f-32) * (5/9));// Calculates the degrees in Celcius
System.out.println(c);
}
}
You are doing integer division, and hence 5 / 9 will give your 0.
Change it to floating point division: -
c = ((f-32) * (5.0/9));
or, do the multiplication first (Remove the brackets from division): -
c = (f-32) * 5 / 9;
Since, f is double. Numerator will be double only. I think this way is better.
use this rather:
c = (int) ((f-32) * (5.0/9));// Calculates the degrees in Celcius
as it involves division and you should not use only ints to get proper division
Use this
System.out.println((5F / 9F) * (f - 32F));
You should try using double instead of int as this would lead to loss of precision. Instead of using the whole formula, use one calculation at one time
Example: Use appropriate casting
Double this = 5/9
F - Double 32
Unless explicitly specified otherwise, Java treats all numbers as integers. Since integers cannot store fractional parts of numbers, when integer division is performed, the remainder is discarded. Therefore: 5/9 == 0
Rohit's solution c = (f-32) * 5 / 9; is probably the cleanest (though the lack of explicit types may cause a bit of confusion).