I am very new to Java and I have to write a program that takes from -40 to 120 Fahrenheit and convert it to Celsius and then display them in two columns with increments of 5 and accurate to one decimal place. I have most of the code finished and I have the right output for the Fahrenheit but I can't figure out how to get the Celsius to print accurate to one decimal place. Anything would be helpful!
package 3;
public class prog2 {
public static void main(String[] args) {
System.out.println("Fahrenheit to Celsius converter from -40F below to 120F");
for(double temp = -40.0; temp <= 120; temp += 5)
{
System.out.printf("%10.1f", temp);
double sum = (temp -32) * (5.0/9.0);
System.out.printf("%5d",(int) sum );
System.out.println();
}
}
}
Change the printing of sum to this:
System.out.printf(" %10.1f", sum );
Formatting is same as for the first column and don't cast the calculated value to int.
you can use DecimalFormat class by sending in the constructor a formating string. In your exemple '#' means one digits and the '.' means decimal point.
check this link for more https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
you can do something like that :
public static void main(String[] args) {
System.out.println("Fahrenheit to Celsius converter from -40F below to 120F");
DecimalFormat df = new DecimalFormat("###.#");
for (double temp = -40.0; temp <= 120; temp += 5) {
System.out.printf("%sC°", df.format(temp));
double sum = (temp - 32) * (5.0 / 9.0);
System.out.printf("= %sF°", df.format(sum));
System.out.println();
}
}
Related
i want to change the decimal spaces of an double, depending on the int value that i use. I Figured out, that i can change the decimal spaces "manually" by changing to 10 or 1000 and so on, but i dont know how to accomplish this, other than changing said values in the code.
My second quest is how to round double values for example 19.657 up to 19.66, or 19.652 down to 19.65 .
Note :
WITHOUT the use of imports and only the default package
I use Java with Eclipse as my IDE
Thank you in advance for your effort :)
double x = 19.657821456;
int y = 3;
x = x*10;
x = (double)((int) x);
x = x /10;
You can use the DecimalFormat class to format your doubles.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(10));
>10.00
This will also round values if they exceed the amount of decimals you specified
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(19.657));
>19.66
You can use Decimal Formate to format double value
Example:
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + df.format(input)); //3.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
df.setRoundingMode(RoundingMode.DOWN);
System.out.println("\ndouble (RoundingMode.DOWN) : " + df.format(input)); //3.14
df.setRoundingMode(RoundingMode.UP);
System.out.println("double (RoundingMode.UP) : " + df.format(input)); //3.15
}
Output :
double : 3.14159265359
double : 3.14
double (RoundingMode.DOWN) : 3.14
double (RoundingMode.UP) : 3.15
Variable number of digits after decimal. Basically same idea as code in question, just using Math methods, calculating the multiplier as needed (10 or 1000 in question):
public static double round(double value, int digits) {
if (digits < 0)
throw new IllegalArgumentException("digits must be non-negative: " + digits);
var mult = Math.pow(10, digits);
return Math.rint(value * mult) / mult;
}
If not allowed to use Math (standard lib, no import needed), we can calculate the multiplier in a loop and use an offset of 0.5 to round to the nearest integer (negative for negative numbers):
public static double round(double value, int digits) {
if (digits < 0)
throw new IllegalArgumentException("digits must be non-negative: " + digits);
var mult = 1.0;
for (var i = 0; i < digits; i++) {
mult *= 10;
}
var offset = value>0 ? 0.5 : -0.5;
return (int) (value * mult + offset) / mult;
}
Be warned that these methods will only work for small number of digits (intermediate results eventually exceeding the integer or even the double value range)
not tested - please test code before using
I am trying to represent the number .0002 as 2.0 x 10 ^ -4.
Here is what I have so far
public static String toScientificNotation(double n) {
int exponent = 0;
if( n < 1){
String doubleValue = Double.toString(Math.abs(n));
int format = doubleValue.indexOf(".");
int decimalPlacesToMove = (doubleValue.length() - (format - 1));
}
No matter what I try i get E in the output. If someone can give me a pseudo code. It would be a great help. I cannot use BigDecimal or anything other than double.
I reworked your method into the following; you can use it as a basis/skeleton to convert the double into the scientific notation you want, avoiding the E altogether. You can expand on it by creating implementations for n > 1 and n < 0
private static String toScienticNotation(double n) {
String result = "";
if (n < 1 && n > 0) {
int counter = 0;
double answer = n;
while (answer < 1) {
answer = answer * 10;
counter--;
}
result = String.valueOf(answer) + " x 10 ^ "
+ String.valueOf(counter);
}
return result;
}
It works by multiplying the input n by 10, counter number of times, until n is greater than 1. This is a substitute formula to manually discover the number of decimal points rather than using the String methods.
The method you were using would work fine, but there's an easier way using formatter:
import java.util.*;
import java.text.*;
import java.math.*;
class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
NumberFormat formatter = new DecimalFormat();
double d = input.nextDouble();
formatter = new DecimalFormat("#.######E0");
String x = formatter.format(d);
System.out.println(x.replace("E","*10^");
}
}
This will print the scientific notation in the decimal format of #.######E0
For example:
If 200 was inputted, the system would return 2 * 10^2.
Here is a method which (hopefully) converts all kinds of doubles to their [-]Factor * 10 ^ [-]Exponent notation. It's explained inside the code.
edit: There is a very elegant solution by UnknownOctopus. Still I will leave this here as it does not use any formatters or such, just doubles and Strings - I understood the question wrongly and assumed that only such primitives were allowed.
public class Main{
/**
* Converts a double to a base10 notation String.
*
* Each String is formatted like this:
*
* [-]Factor * 10 ^ [-]Exponent
*
* where both, Factor and Exponent, are integer values.
*
* #param number the number to convert
* #return a base10 notation String.
*/
public static String toScientificNotation(double number) {
String s = String.valueOf(number);
int indexPZero = s.indexOf(".0"); // mostly to check if .0 is the end
int exponent = 0; // simplest case: *10^0
// Check if the String ends with exactly .0
if (indexPZero == s.length() - 2) {
// If the string also has 0s in front of the period, shift those to the
// right
while(s.contains("0.")) {
number /= 10;
exponent += 1;
s = String.valueOf(number);
}
// if the string ends in .0 and has no zeros in front of the period we
// can format it:
return String.valueOf(number) + " * 10 ^ " + exponent;
}
// If the String does not end in .0, we need to shift to the left.
// Additionall
while (indexPZero != s.length() -2) {
// in case we suddenly reach the scientific notation just substitute it
s = s.toLowerCase();
if (s.contains("e")) {
return s.substring(0,
s.indexOf("e")) + " * 10 ^ " + s.substring(s.indexOf("e")+1);
}
// otherwise shift left and reduce the exponent
number *= 10;
exponent -= 1;
s = String.valueOf(number);
indexPZero = s.indexOf(".0");
}
// If we end up here, just write out the number and the exponent.
return String.valueOf(number) + " * 10 ^ " + exponent;
}
public static void main(String... args) {
double[] vals = { 1, 0.2, 23.4, -32.00004, 0.0002, 10.0 };
for(double val : vals) {
System.out.println(val + " becomes " + toScientificNotation(val));
}
}
}
Output:
1.0 becomes 1.0 * 10 ^ 0
0.2 becomes 2.0 * 10 ^ -1
23.4 becomes 234.0 * 10 ^ -1
-32.00004 becomes -3200004.0 * 10 ^ -5
2.0E-4 becomes 2.0 * 10 ^ -4
10.0 becomes 1.0 * 10 ^ 1
I need to create a program that will output a formatted two column list converting Celsius to Fahrenheit ending at the temperature 40 degrees from the starting temperature, which is entered by the user. It's supposed to look like this: (except it counts up from whatever the user enters as Celsius)
I've been working at this for hours and I have no idea how to fix it. Not only is the Celsius starting at 1 (which I think is that (cel=1;) bit), but I have no idea why Fahrenheit is not calculating correctly.
Here's my current source:
import java.util.Scanner;
public class TempTable {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
float cel;
double column;
double Fahrenheit;
final double C_2_F = (9.0 / 5.0);
System.out.println("Enter your city's temperature in Celsius.");
cel = kb.nextFloat();
System.out.println("Here is the conversion from " + cel);
System.out.printf("%2s%12s%n", "Celcius", "Fahrenheit");
for (cel = 1; cel <= 10; cel++) {
column = cel;
for (Fahrenheit = 1; Fahrenheit <= 10; Fahrenheit++) {
Fahrenheit = cel * C_2_F + 32;
System.out.printf("%2.0f%12.0f%n", cel, Fahrenheit);
}
}
kb.close();
}
}
Fix your loop to not reset 'Fahrenheit' each time through.
for ( Fahrenheit = 1; Fahrenheit <=10; Fahrenheit++) {
Fahrenheit = cel * C_2_F + 32;
System.out.printf("%2.0f%12.0f%n",cel,Fahrenheit);
}
To
for ( Fahrenheit = 1; Fahrenheit <=10; Fahrenheit++) {
double f = cel * C_2_F + 32;
System.out.printf("%2.0f%12.0f%n",cel,f);
}
Would be one way. Also rename 'Fahrenheit' to 'fahrenheit'
Actually, that's only one issue. That's just going to print out the same value 10 times since 'cel' and 'C_2_F' don't change during the loop...
I need to convert Fahrenheit to Celsius in a Java program with methods, a for loop statement, and no user input. It is supposed to display Fahrenheit temperatures 0 through 20 and it's Celsius conversions. Any solutions?
import java.util.Scanner;
public class celsiusTempTable
{
public static void main(String[] args)
{
System.out.println("Fahrenheit to Celsius Conversion Table");
double tempC = celsiusConversion(tempC);
int tempF = fahrenheit(tempF);
displayData(tempF, tempC);
}
public static int fahrenheit(int F)
{
for(F = 0; F <= 20; F++)
{
return F;
}
}
public static double celsiusConversion(double C)
{
Scanner input = new Scanner(System.in);
for(int F = 0; F <= 20; F++)
{
C = (5.0/9.0) * (F - 32);
return C;
}
}
public static void displayData(int F, double C)
{
for(F = 0; F <= 20; F++)
{
System.out.println("\nThe temperature in Fahrenheit is: " + F);
System.out.println("The temperature in Celsius is: " + C);
}
}
}
I'll only give hints.
Without user input. So forget about using a Scanner and System.in.
You need to understand what method arguments and method return values are. Arguments are usually the inputs of a method. And the return value is the output of the method. You're being asked to translate a temperature in fahrenheit degrees to a temperature in celsius degrees. This is a perfect situation where a method is useful. The input of the translation method is thus a unique integer value (the temperature in fahrenheit degrees), and the output is another single integer value (the temperature in celsius degrees).
You must do that 21 times. Once with 0 as input, once with 1 as input, etc. until 20. This means you need a loop, and that at each iteration, you will translate the current temperature (0, 1, 2, etc.) into celsius degrees by calling the translation method, and print the result. Read your text book about for loops. This part should be in the main method.
A quick search and have found the following:
Error: celsius cannot be resolved to a variable
Java Fahrenheit to Celsius loop (with methods)
Fahrenheit to Celsius conversion
Celsius/Fahrenheit conversion error
i have written a program to find out the number of digit in a given number in java. Is it a good way to do it and what is the time complexity of the program:
import java.util.*;
public class Inst {
/**
* #param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
for(int n=0;n<200000;n++)
{
double b=Math.pow(10, n);
double d=a/b;
if(d>=0 & d<=9)
{
System.out.println("The number has "+(n+1)+" DIGITS");
break;
}
}
}
}
How about this?
double input = Input;
int length = (input + "").length();
import java.util.*;
public class JavaLength {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Double d = sc.nextDouble();
String dString = d.toString();
System.out.println(d);
if(dString.contains(".")){
System.out.println("Total Characters: " + (dString.length() -1 ));
}else{
System.out.println("Total Characters: " + (dString.length()));
} /*-1 for the '.' in between, if it exists!*/
}
FWIW, the most efficient way to test the number of (decimal) digits needed to represent an integer will be a tree of if / else tests. The complexity will be O(1), but the code will be UGLY (but portable); e.g.
int num = ...
if (num >= 0)
if (num < 1000000)
if (num < 10000)
if (num < 100)
if (num < 10)
return 1
else
return 2
else
...
else
...
else
...
else
...
Using pow / log is not generally a good solution, as there may be a number close to a power of ten that rounds to the next integer. In double precision one should be able to precisely store all 15 digit numbers for which log10 should be absolutely < 15. In reality log10(10^15 - 100) still rounds to 15.
One will be stuck with the same algorithms, that are internally used in decimal to string conversions:
trial division:
while (i > 0) { i=i/10; count++; }
trial multiplication:
j=10; while (i >= j) { j*=10; count++; }
trial division from msb to lsb converting to string;
j=10000000; while (i>0) {
while (i>=j) { digit++;i-=j;};
j/=10; *str++=digit+'0'; digit=0:
}
Binary to bcd conversion using double dabble algorithm where each digit is represented by reduced set of hexadecimal digits (omitting a-f).
This logic was originally written in c++, but i believe is the best way to find number of digits, store them in reverse order and find sum of digits.
int n;
int count=0, sum=0;
int j=0;
int ar[10]; //array to store digits
cin>> n; //input number
do{
if((n/10)==0){
count++;
ar[j]=n;
break;
}
else{
count++;
ar[j]= (n%10);
j++;
n=int(n/10);
}
}
`
while((n/10)!=0||(n%10)!=0);
cout<<"The number of digits is: "<<count<<"\n"<<"The reverse number is: ";
for(int u=0;u<count;u++){
cout<<ar[u];
sum+=ar[u];
}
cout<<"\n"<< "Sum of digits is: "<< sum;
}`