I'm trying to make a class that has a single constructor that accepts a temperature (in Celsius) as a double, and if the temperature is less than -273.15, it sets it to -273.15. It also calculates other temperatures for different units of measurement, but that's not important. For some reason, I'm getting a logic error that doesn't correct inputs less than -273.15 to -273.15.
public class TemperatureC
{
private double temperature;
public TemperatureC(double c)
{
if (temperature < -273.15)
{
temperature = -273.15;
}
else
{
temperature = c;
}
}
public TemperatureC()
{
temperature = -273.15;
}
public double getC()
{
return temperature;
}
public double getF()
{
return ((temperature * 1.8) + 32);
}
public double getK()
{
return (temperature + 273.15);
}
public void setC(double c)
{
if (temperature >= -273.15)
{
temperature = c;
}
}
}
And this is what's using the class.
import java.util.Scanner;
public class TemperatureTester
{
public static void main(String[] args)
{
Scanner thermometer = new Scanner(System.in);
TemperatureC temp = new TemperatureC();
System.out.printf("Please enter the initial temperature:");
double intialTemp = thermometer.nextDouble();
temp.setC(intialTemp);
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());
System.out.printf("Please enter a new temperature:");
double secondTemp = thermometer.nextDouble();
temp.setC(secondTemp);
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());
}
}
And here is my faulty output:
Please enter the initial temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
Please enter a new temperature:-900
The current temperature in Celsius is:-900.0
The current temperature in Fahrenheit is:-1588.0
The current temperature in Kelvin is:-626.85
It should correct inputs less than -273.15 to -273.15.
Your issue is you are checking the default value of the constructor. Either set temperature to c first or check against c.
public TemperatureC(double c)
{
temperature = c;
if (temperature < -273.15)
{
temperature = -273.15;
}
that should work, as a side effect the else is no longer needed
You're only checking for temperate < -273.15 in the constructor, so any time you call setC then you won't correct it. Additionally, in the setC method you don't set the temperature at all unless it's at or above -273.15
You could remove the constructor altogether since you aren't calling it anyway and change the logic in setC to check for temperates < -273.15
Related
I am new to java, and I have just learned to use methods. I wrote a simple program to convert temperatures:
public class TempConversion {
double temperature;
public TempConversion() {
}
public double celsiusToKelvin(double celsiusTemp) {
temperature = celsiusTemp + 273.15;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double celsiusToFahrenheit(double celsiusTemp) {
temperature = celsiusTemp * 9 / 5 + 32;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double fahrenheitToCelsius(double fahrenheitTemp) {
temperature = (fahrenheitTemp - 32) * 5 / 9;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double fahrenheitToKelvin(double fahrenheitTemp) {
temperature = (fahrenheitTemp + 459.67) * 5 / 9;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double kelvinToCelsius(double kelvinTemp) {
temperature = kelvinTemp - 273.15;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public double kelvinToFahrenheit(double kelvinTemp) {
temperature = kelvinTemp * 9 / 5 - 459.67;
System.out.println("Converted temperature: " + temperature);
return temperature;
}
public static void main(String[] args) {
TempConversion temp = new TempConversion();
temp.celsiusToFahrenheit(38);
temp.celsiusToKelvin(0);
}
}
Right now, however, for the program to convert the temperatures, I have to call each method in the code itself. If I understood right, I can use a Scanner class to get user input, so how would I call one of methods while also using Scanner to get user input. I'm not sure if my question makes sense, but I can try clarifying if asked.
Perhaps It is not the best solution, but I think It is pretty graphic to explain the usefulness of the scanner function in Java.
Just copy and paste this into the main area of your code:
public static void main(String[] args) {
TempConversion temp = new TempConversion();
temp.celsiusToFahrenheit(38);
temp.celsiusToKelvin(0);
Double number;
String input;
String output;
Scanner sc = new Scanner(System.in);
System.out.println("Input a number, only double allowed");
number = sc.nextDouble();
sc.nextLine();
System.out
.println("Input the first letter of the source unit. c for celsius, f for fahrenheit or k for kelvin");
input = sc.nextLine();
System.out
.println("Input the first letter of the target unit. c for celsius, f for fahrenheit or k for kelvin");
output = sc.nextLine();
if (input.equals("c")) {
if (output.equals("k")) {
temp.celsiusToKelvin(number);
} else if (output.equals("f")) {
temp.celsiusToFahrenheit(number);
}
} else if (input.equals("f")) {
if (output.equals("c")) {
temp.fahrenheitToCelsius(number);
} else {
temp.fahrenheitToKelvin(number);
}
} else {
if (output.equals("c")) {
temp.kelvinToCelsius(number);
} else {
temp.kelvinToFahrenheit(number);
}
}
sc.close();
}
About how Scanner actually works It is very easy to find it out on the internet, but once you have declared a Scanner object there is no need to declare a new Scanner every time you want to save an input for something else, just as It has been done above, you can just re-use it many times you want.
Once you change from one object to another (in this problem is from keeping the double and now wwe want a String) you have to clear the buffer (there It is that sc.nextLine(); sentence).
And, after all this, remember to close the scanner. It is not mandatory, but if not, you will get a "warning" or something like that.
I've been working on this code and everything seems to be working, but when MyProgrammingLab actually runs my code it says there is a problem with my standard output.
Here is the problem:
Write a Temperature class that will hold a temperature in Fahrenheit and provide methods to get the temperature in Fahrenheit, Celsius, and Kelvin. The class should have the
following field:
• ftemp: a double that holds a Fahrenheit temperature.
The class should have the following methods :
• Constructor : The constructor accepts a Fahrenheit temperature (as a double ) and stores it in the ftemp field.
• setFahrenheit: The set Fahrenheit method accepts a Fahrenheit temperature (as a double ) and stores it in the ftemp field.
• getFahrenheit: Returns the value of the ftemp field as a Fahrenheit temperature (no conversion required)
• getCelsius: Returns the value of the ftemp field converted to Celsius. Use the following formula to convert to Celsius:
Celsius = (5/9) * (Fahrenheit - 32)
• getKelvin: Returns the value of the ftemp field converted to Kelvin. Use the following formula to convert to Kelvin:
Kelvin = ((5/9) * (Fahrenheit - 32)) + 273
Demonstrate the Temperature class by writing a separate program that asks the user for a
Fahrenheit temperature. The program should create an instance of the Temperature class ,
with the value entered by the user passed to the constructor . The program should then
call the object 's methods to display the temperature in the following format (for example,
if the temperature in Fahrenheit was -40):
The temperature in Fahrenheit is -40.0
The temperature in Celsius is -40.0
The temperature in Kelvin is 233.0
And now here is my code:
import java.io.*;
import java.util.Scanner;
public class Temperature
{
private double ftemp;
public Temperature(double ftemp)
{
this.ftemp = ftemp;
}
public void setFahrenheit(double ftemp)
{
this.ftemp = ftemp;
}
public double getFahrenheit()
{
return ftemp;
}
public double getCelsius()
{
return (5.0/9.0) * (ftemp - 32.0);
}
public double getKelvin()
{
return (5.0/9.0) * ((ftemp - 32.0) + 273.0);
}
}
class myTemperature
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double input;
System.out.print("Enter a Fahrenheit temperature:");
input = keyboard.nextDouble();
Temperature temp1 = new Temperature(input);
System.out.println("The temperature in Fahrenheit is " + temp1.getFahrenheit());
System.out.println("The temperature in Celsius is " + temp1.getCelsius());
System.out.println("The temperature in Kelvin is " + temp1.getKelvin());
}
}
These are the errors it gives me:
http://imgur.com/gallery/0D2RkW7/new
I don't have enough rep to post images, sorry!
I really just don't understand what the problem could be, any help would be greatly appreciated.
public double getKelvin()
{
return ((5.0/9.0) * (ftemp - 32.0)) + 273.0;
}
Note the changes in ()
I have to allow the user to choose which conversion to do, and what degree to start at, then print the conversion starting at that degree up to the next 9 (10 conversions). And I have to write this using a callback function. Also there is a menu in the beginning. I have an "else without if" at line . Also my callback function is not calculating numbers correctly. How do I resolve this error and fix my callback function?
import java.util.Scanner;
public class FahrToCel {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
double choice = 0;
double fahrenheit = 0;
double celsius = 0;
double answer = 0;
//print the welcome message and the menu options for the user
System.out.printf("Welcome to Candace's Fahrenheit and Celsius "
+ "convertor. ");
System.out.printf("Please choose one of the following options: \n"
+ " Press 0 to exit \n Press 1 to to convert to Celsius \n"
+ " Press 2 to convert to Fahrenheit > ");
choice = input.nextInt();
//print what happens when the user hits a button
if (choice == 0){
// the user is going to exit the game
System.out.printf("Well hopefully you can play again soon! :) ");
} else {
//perform code for the operation
for ( double i = fahrenheit; i >-100; i-=10 ){
if (choice == 1) {
// it will convert from fahrenheit to celsius
System.out.printf("Please pick a number in Fahrenheit: > ");
fahrenheit = input.nextDouble();
celsius = FahrToCel();
System.out.printf("%f ", i);
}
}
for ( double i = celsius; i >-10; i-=10 ){
if (choice == 2){
// it will convert from celsius to fahrenheit
System.out.printf("Please pick a number in celsius: > ");
celsius = input.nextDouble();
fahrenheit = CelToFahr();
System.out.printf("%f ", i);
}
}
} else {
System.out.printf("I'm sorry, I did not ask you to enter that "
+ "number. ");
}
}
public static double CelToFahr(){
double celsius = 0;
double fahrenheit = 0;
celsius = (fahrenheit - 32) * (5.0/9.0);
return celsius;
}
public static double FahrToCel( ){
//perform the conversion for fahrenheit to celsius
double celsius = 0;
double fahrenheit = 0;
fahrenheit = ((9.0/5.0) + 32) * celsius;
return fahrenheit;
}
}
You are looking for a structure like this
if (choice == 0){
// ...
}
else if (choice == 1) {
for ( double i = fahrenheit; i >-100; i-=10 ){
// ...
}
}
else if (choice == 2) {
for ( double i = celsius; i >-10; i-=10 ){
// ...
}
}
else {
// ...
}
Right now you have some if statements inside of an else and your scope is getting confused. Your loops would then go inside those else if statements. Also note that you are doing the conversion many times, but printing the initial value entered each time, not the converted temperature.
Among other things, (EDIT) ONE OF your functions is not quite right. Since they involve math, I'm offering my revisions instead of hints.
I don't know if you want to pass in the value you're converting from, but doing so would make it better.
You definitely don't want to set both celsius and fahrenheit to zero in both functions.
public static double FahrToCel(double fahrenheit ){
double celsius;
celsius = (fahrenheit - 32) * (5.0/9.0);
return celsius;
}
public static double CelToFahr( double celsius){
//perform the conversion for fahrenheit to celsius
double fahrenheit;
fahrenheit = ((9.0/5.0) ) * celsius + 32;
return fahrenheit;
This would mean that inside your for loops, the calls to the functions would have to be something like:
celsius = input.nextDouble();
fahrenheit = CelToFahr(celsius);
But I'm not sure you should input the next value of celsius, if I'm reading the instructions and intent of the for loops correctly.
Maybe you want this instead of inputting:
celsius = i;
I'm fairly new at Java, even newer at trying to understand OOP, so don't make fun of my lack of understanding, please.
I'm trying to design a program that will get the user to input a temperature in either Fahrenheit or Celsius, then the program will determine what that temperature is in the other measurement.
Can anyone give me any tips on if I am even going in the right direction?
This is what I have so far, and keep in mind that this is pretty much my first attempt at OOP, so it probably looks like a mess.
import java.io.*;
class tempConvert
{
//declaring variables
int c; //variable for "Celcius"
int f; //variable for "Fahrenheit"
//method to convert celcius to fahrenheit
public void celToFahr
{
InputStreamReader inStream = new InputStreamReader (System.in);
BufferedReader temp = new BufferedReader (inStream);
String cel;
System.out.println ("Please input temperature in celcius:");
cel = temp.readLine ( );
c = Integer.parseInt (cel);
f = (9.0 / 5.0) * c + 32;
System.out.println ("The temperature in Fahrenheit is " + f + " degrees.");
}
//method to convert fahrenheit to celcius
public void fahrToCel
{
BufferedReader temp = new BufferedReader (inStream);
String fahr;
System.out.println ("Please input temperature in fahrenheit:");
fahr = temp.readLine ( );
f = Integer.parseInt (fahr);
c = (5.0 / 9.0) * (f - 32);
System.out.println ("The temperature in Celcius is " + c + " degrees.");
}
}
Here's an OOP concept you could use: value types. Value types are objects that hold a value like the primitive wrappers Integer, Double, etc., and other classes like BigDecimal.
Now, here are three ideas for your value type: 1) One class that has two fields to represent the value and the scale; 2) A different class for every temperature scale; 3) One class that internally always represents the temperature using the same scale and externally converts it to other scales. When choosing one of these designs, ponder the complexity of the conversion methods you will have to write, and the complexity of client code that would use the little API you are creating, especially if you ever wanted to add support for more temperature scales.
OUTPUT
output
Default temperatures: 0.0C OR 32.0F
1.Convert Celcius to Fareiheit
2.Convert Fareiheit to Celcius
3.Update default temperature
1
Enter temperature in Celcius to convert into Farenheit
60
60.0C = 92.0F
Default temperatures: 0.0C OR 32.0F
1.Convert Celcius to Fareiheit
2.Convert Fareiheit to Celcius
3.Update default temperature
2
Enter temperature in Farenheit to convert into Celcius
-10
-10.0F = -23.333333333333336C
Default temperatures: 0.0C OR 32.0F
1.Convert Celcius to Fareiheit
2.Convert Fareiheit to Celcius
3.Update default temperature
3
Enter temperature in celcius
25
Default temperatures: 25.0C OR 57.0F
1.Convert Celcius to Fareiheit
2.Convert Fareiheit to Celcius
3.Update default temperature
Temperature.java
public interface Temperature {
public double getTempInFarenheit(double celcius);
public double getTempInCelcius(double farenheit);
public double getCurrentTemp();
public double setDefaultTemp(double defaultCelcius);
}
TemperatureImpl.java
public class TemperatureImpl implements Temperature {
private double defaultTemp=0.0;
public double Temperature(double defaultTemp){
return this.defaultTemp=defaultTemp;
}
#Override
public double getTempInFarenheit(double celcius) {
return ((double)(9/5)*(celcius+32.0));
}
#Override
public double getTempInCelcius(double farenheit) {
return ((double)5/9*(farenheit-32.0));
}
#Override
public double getCurrentTemp() {
return defaultTemp;
}
#Override
public double setDefaultTemp(double defaultCelcius){
return this.defaultTemp = defaultCelcius;
}
}
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
TemperatureImpl temp = new TemperatureImpl();
while(true){
System.out.println("Default temperatures: "+temp.getCurrentTemp()+"C OR "+temp.getTempInFarenheit(temp.getCurrentTemp())+"F");
System.out.println("1.Convert Celcius to Fareiheit");
System.out.println("2.Convert Fareiheit to Celcius");
System.out.println("3.Update default temperature");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
switch (input) {
case 1: System.out.println("Enter temperature in Celcius to convert into Farenheit");
double celcius = sc.nextDouble();
System.out.println(celcius+"C = "+temp.getTempInFarenheit(celcius)+"F");
break;
case 2: System.out.println("Enter temperature in Farenheit to convert into Celcius");
double fareinheit = sc.nextDouble();
System.out.println(fareinheit+"F = "+temp.getTempInCelcius(fareinheit)+"C");
break;
case 3: System.out.println("Enter temperature in celcius");
temp.setDefaultTemp(sc.nextDouble());
break;
default:
System.out.println("Invalid input.");;
}
}
}
}
I wrote the whole thing all over again since as said in the comments you did not write in OOP:
This is the main OOP part, a class that creates objects of temperature.
package com.example.tomer2;
public class temp {
double c; // for celcius
double f; // for farenheit
boolean isfarenheit;
public temp( double temp , boolean isfarenheit) {
if(isfarenheit){
this.f = temp;
this.c = this.farenToCelc(temp);
}
else{
this.c = temp;
this.f = this.celciusToFar(temp);
}
}
private double celciusToFar(double celcius){
return ((double)(9/5)*(celcius+32.0));
}
public double farenToCelc(double farenheit) {
return ((double)5/9*(farenheit-32.0));
}
}
Here is the class with the main function:
package com.example.tomer2;
public class temp {
double c; // for celcius
double f; // for farenheit
boolean isfarenheit;
public temp( double temp , boolean isfarenheit) {
if(isfarenheit){
this.f = temp;
this.c = this.farenToCelc(temp);
}
else{
this.c = temp;
this.f = this.celciusToFar(temp);
}
}
private double celciusToFar(double celcius){
return ((double)(9/5)*(celcius+32.0));
}
public double farenToCelc(double farenheit) {
return ((double)5/9*(farenheit-32.0));
}
}
I did not do complete tests for this.
Using encapsulation fields,
Public class Temp{
private double cel;
private double far;
public double getCel(){
return ((far-32)*5/9);
}
public void setCel(double cel){
this.cel=cel;
}
public void getfar(){
return ((cel*9/5)+32);
}
public void setfar(dofaruble far){
this.cel=cel;
}
}
Main method:
class A{
public static void main(String []args){
Temp obj=new obj();
obj.setcel(12.4);
obj.setfar(34.5);
System.out.println("Celcious"+obj.getcel());
System.out.println("fahrenheit"+obj.getfar());
}
}
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}