java program not desired outcome - java

import java.util.Scanner;
public class FtoC
{
public static void main(String[] args)
{
double DegreesF, DegreesC;
System.out.print("Enter temperature in Fahrenheit:");
` Scanner sc = new Scanner(System.in);
DegreesF = sc.nextInt();
DegreesC = 5*(DegreesF-32)/9;
System.out.print(DegreesF + " degrees Fahrenheit" + " is " + DegreesC + " degrees Celsius.");
}
}
i get the output :Enter temperature in Fahrenheit:72
72.0 degrees Fahrenheit is 22.22222222222222 degrees Celsius.
I need that 72 degrees Fahrenheit to be a whole number, without the decimal part. please help.

I need that 72 degrees Fahrenheit to be a whole number, without the
decimal part
You could store it initially as an int, and not a double:
int DegreesF;
double DegreesC;
Which will print:
72 degrees Fahrenheit is 22.0 degrees Celsius.
Or cast it as an int in your print statement:
System.out.print((int)DegreesF + " degrees...
Although better to go with the first way.
Also, you should then specify the Celsius value (perhaps to two decimal points):
One way would be to use DecimalFormat:
DecimalFormat df = new DecimalFormat(".##");
and print it like:
df.format(DegreesC)

Since you only Scan for an int value, simply define DegreesF as an int
int DegreesF;
rather than
double DegreesF;
since Integers don't have a decimal point you won't have the problem any more
to get correct Celcius value do this:
DegreesC = 5*((double)DegreesF-32)/9;

Related

How to combine two simple programs into one

How can I combine two small programs I created?
They are conversions of Farenheit to Celsius and vice versus. When I join the two together, I clearly have double/repeating variables. Not quite sure how/what to change.
The goal is to combine the two programs so it will ask the user to choose one, (F or C) and then direct the user to input an integer to convert. Not sure if I need to create these as two objects of my class? Or how to direct a choice, maybe using Switch?
Below is one conversion used, the formula is the same just inverse.
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a degree in Fahrenheit: ");
double fahrenheit = input.nextDouble();
double celsius =(5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit + " is " + celsius + " in Celsius") ;
}
}
I think you are right that we can simplify the code using a single switch statement - or even an if statement in this case.
Try maybe this:
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String convertFrom = userInput.nextLine();
double C, F, convertedDegrees;
if (convertFrom.equals("F")) {
// Convert Fahrenheit to Celsius
} else if (convertFrom.equals("C")) {
// Convert Celsius to Fahrenheit
convertedDegrees = userInput.nextDouble();
F = (convertedDegrees * 1.8) + 32;
System.out.println(F);
} else {
System.out.println("Invalid input. Please type 'C' or 'F' to indicate whether you wish to convert Celsius or Fahrenheit degrees.");
}
}

When I place my doubles on top, the program doesn't run properly

Assignment: Variables
This program prompts the user to enter a temperature between -58°F and
41°F and a wind speed greater than or equal to 2 then displays then
displays the wind-chill temperature.
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Tempurature
double temperature = input.nextDouble();
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
}
This seems to be a school assignment. However, it seems like you have already completed the bulk of the work. Congratulations! Now, I feel like the issue here can be solved by explaining why your program does not work if "the doubles are on top". I hope that my answer can help you better understand the way java interprets your code!
Without further ado, programming languages of all types have variables. Java is no different. For example...
double number = 0.0; // Java variable declaration
number = 0.0 # Python variable declaration
var number = 0.0 // JavaScript variable declaration
Your code is going to be executed from the top down. An illustration of this would look like the following.
int money = 0;
System.out.println(money);
money = 10;
System.out.println(money);
money = 9000;
System.out.println("I have over " + money);
This will output
0
10
I have over 9000
However, if you wrote this code like the following
System.out.println(money);
int money = 0;
You will get an error! This is because the execution has not seen that money is even a thing yet! This would be like brushing your teeth without a tooth brush. You can't because you don't have a brush.
Therefore, the same applies to your program.
public static void main(String[] args) {
double temperature = input.nextDouble();
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Tempurature
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
Notice temperature above the scanner line. Input is a object you create to read in that double. If you try to use this before you create your input object the program has no idea what that input object is!
Just rearrange the code like below
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
// Tempurature
double temperature = input.nextDouble();
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
// Windspeed
double speed = input.nextDouble();
// Compute the wind chill tempurature
double windChill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(speed,
0.16) + 0.4275 * temperature *
Math.pow(speed, 0.16);
// Display result
System.out.println("The wind chill tempurature is " + windChill);
}
}
but there is no problem related to double, :)
Thanks everyone. I got it.
/* Assignment: Variables
This program prompts the user to enter a temperature between -58°F and 41°F
and a wind speed greater than or equal to 2 then displays then displays the
wind-chill tempurature.
*/
// Imports util.Scanner
import java.util.Scanner;
public class Windchill {
public static void main(String[] args) {
// Declare variables
double temperature;
double windspeed;
double wind_chill;
// Create a Scanner object to read input
Scanner input = new Scanner(System.in);
// Prompt the user to enter a temperature between -58F and 41F.
System.out.print("Enter the temperature in Fahrenheit " +
"between -58\u00b0F and 41\u00b0F: ");
temperature = input.nextDouble();
// Prompt the user to enter the wind speed greter than or equal to 2.
System.out.print("Enter the wind speed (>= 2) in miles per hour: ");
windspeed = input.nextDouble();
// Display result
wind_chill = 35.74 + 0.6215 * temperature -
35.75 * Math.pow(windspeed, 0.16) +
0.4275 * temperature * Math.pow(windspeed, 0.16);
System.out.println("The wind chill temprature is " + wind_chill);
}
}

Trying to output solution to math equation always results in 0

I am a complete beginner with java and coding altogether and am trying to make a program that solves two equations based on what a user has inputted into the program. I've tried changing the variable types to long, int, double, but nothing changes. The result is always 0 or 0.0 Any help would be much appreciated.
package pa2;
import java.util.Scanner;
public class GravitationalForce
{
public static void main(String[] args)
{
System.out.println("Please enter the name of the planet and its weight in quintillion kilograms");
Scanner myScanner = new Scanner (System.in);
String planetName = myScanner.next();
int planetWeight = myScanner.nextInt();
System.out.println("Enter the weight of the person in kilograms");
double personWeight = myScanner.nextDouble();
System.out.println("Please enter the radius of the planet Alderaan in million meters");
double planetRadius = myScanner.nextDouble();
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
Double force = gravitationalConstant*(planetWeight*Math.pow(10, 18)*personWeight)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6);
Double gravity = gravitationalConstant*(planetWeight*Math.pow(10, 18)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6));
System.out.println("The gravitational force of planet " + planetName + " on the person is " + force + " Newtons");
System.out.println("The gravity of the planet " + planetName + " is " + gravity + " meters per second squared");
}
}
6.673*Math.pow(10,-11) is < 1, so if you cast it to long, it becomes 0.
change
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
to
double gravitationalConstant = 6.673*Math.pow(10,-11);

Temperature conversion using objects in java

So i am currently writing a program using objects where the user enters an initial temperature, then the program has to compute it into Celsius, which would just be the user input, then to Fahrenheit and then to kelvin. The class also has a single constructor that accepts an initial temperature provided as a double argument. If this argument is < -273.15, set it to -273.15. I thought I was on the right track but when i compiled it, it wasn't doing what i wanted, any tips on how I can fix it?
With this code, the output gives me
Please enter the initial temperature: 20
The current temperature in Celsius is: 0.0
The current temperature in Fahrenheit is: 32.0
The current temperature in Kelvin is: 273.15
which isn't right... any tips?
//blueprint
public class TemperatureC{
private double temperatureC;
public TemperatureC(){
if(temperatureC<-273.15){
temperatureC = -273.15;}
else{}
}
public void setC(double c){
temperatureC = c;
}
public double getC(){return temperatureC;}
public double getF(){return (temperatureC * 1.8) + 32;}
public double getK(){return temperatureC + 273.15;}
}
//code
import java.util.Scanner;
public class TemperatureTester{
public static void main(String[] args){
TemperatureC temp = new TemperatureC();
double initialTemperature;
double celsius=temp.getC();
double fahrenheit=temp.getF();
double kelvin=temp.getK();
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the initial temperature: ");
initialTemperature = keyboard.nextDouble();
//TemperatureC temp = new TemperatureC();
System.out.println("The current temperature in Celsius is: " + celsius);
System.out.println("The current temperature in Fahrenheit is: "+fahrenheit);
System.out.println("The current temperature in Kelvin is: "+kelvin);
}
}
You are assigning the values of celsius, fahrenheit, and kelvin before you know the temperature value. You want your tester to look more like this
public static void main(String[] args) {
TemperatureC temp = new TemperatureC();
double initialTemperature;
Scanner keyboard = new Scanner(System.in);
initialTemperature = keyboard.nextDouble();
temp.setC(initialTemperature);
System.out.println("The current temperature in Celsius is: " + temp.getC());
System.out.println("The current temperature in Fahrenheit is: "+temp.getF());
System.out.println("The current temperature in Kelvin is: "+temp.getK());
}
So the operations are now done after the temperature of initialTemperature is set.

Float cannot be dereferenced - using BigDecimal

I am getting an error trying to code a program which calculates interest on a loan, and displays information back with certain decimal positions. I need the loanInterest to display at 3.546%, or something like that with 3 decimal places. I was able to get the totalInterest to display properly, but I dont know if this is because it was a new value I just established. When I try to run my program as seen below, I get a "float cannot be dereferenced" error.
public class SarahShelmidineModule2Project {
public static void main(String[] args) {
//Being programing for Module 2 project
// Welcome the user to the program
System.out.println("Welcome to the Interest Calculator");
System.out.println(); // print a blank line
// create a Scanner object named sc
Scanner sc = new Scanner(System.in);
// perform interest calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get info from user on loan amount and interest rates and store data
System.out.print("Enter loan amount: ");
double loanAmount = sc.nextDouble();
System.out.print("Enter interest rate: ");
float loanInterest = sc.nextFloat();
// calculate the interest and convert to BigDecimal and rounding for totalInterest
BigDecimal decimalloanAmount = new BigDecimal (Double.toString(loanAmount));
BigDecimal decimalloanInterest = new BigDecimal (Double.toString(loanInterest));
BigDecimal totalInterest = decimalloanAmount.multiply(decimalloanInterest);
totalInterest = totalInterest.setScale(2, RoundingMode.HALF_UP);
loanInterest = loanInterest.setScale(3, RoundingMode.HALF_UP);
System.out.println(); // print a blank line
// display the loan amount, loan interest rate, and interest
// also format results to percent and currency
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
String message = "Loan amount: " + currency.format(loanAmount) + "\n"
+ "Interest rate: " + percent.format(loanInterest) + "\n"
+ "Intrest: " + currency.format(totalInterest) + "\n";
System.out.println(message);
// inquire if user would like to continue with application
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
Below is the error I get when I run this:
Welcome to the Interest Calculator
Enter loan amount: 10932
Enter interest rate: .0934
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - Erroneous sym type: <any> at
sarahshelmidinemodule2project.SarahShelmidineModule2Project.main(SarahShelmidineModule2Project.java:45)
Just change
float loanInterest = sc.nextFloat();
with
BigDecimal loanInterest = new BigDecimal(sc.nextFloat());
and you will resolve "float cannot be derefenced" since float is a primitive type and has not method setScale.
About printing right number of decimals, use something like this:
String currencySymbol = Currency.getInstance(Locale.getDefault()).getSymbol();
System.out.printf("%s%8.5f\n", currencySymbol, totalInterest);
This code will use 5 decimals, but be sure that your BigDecimal scale is at least 5, otherwise you will get not significant zeros.

Categories