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());
}
}
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 have quickly made a small program that converts Fahrenheit into Celsius and Celsius into Fahrenheit but when I try to use the one variable it doesn't do all of the steps. I can understand why but I cannot figure out how I can prevent it from only doing the last operation because I want it to do all of the operations in order.
As far as im aware if I use the same variable for all of the operations such as the -32, *5 and /9 it will only do the last one because I have used = to assign that as the value but I am unsure whether this is the reason or not, any help would be appreciated, thanks.
public class TempConversion{
//FahrenheitSteps
private int Fahrenheit;
private int FahrenheitA;
private int FahrenheitB;
private int FahrenheitC;
//CelciusSteps
private int Celcius;
private int CelciusA;
private int CelciusB;
private int CelciusC;
//Constructor
public TempConversion(){
Fahrenheit = 0;
Celcius = 0;
}
//Convert Fahrenheit to celcius
public void FahrenheitToCelcius(int Fahren){
CelciusA = Fahren - 32;
CelciusB = CelciusA * 5;
CelciusC = CelciusB / 9;
System.out.println(CelciusC + " Is the celcius equivalent");
}
//Convert Celcius to fahrenheit
public void CelciusToFahrenheit(int Celc){
FahrenheitA = Celc * 9;
FahrenheitB = FahrenheitA / 5;
FahrenheitC = FahrenheitB + 32;
System.out.println(FahrenheitC + " Is the fahrenheit equivalent");
}
}
You can combine the following three lines:
CelciusA = Fahren - 32;
CelciusB = CelciusA * 5;
CelciusC = CelciusB / 9;
into
Celcius = (Fahren-32) * 5 / 9;
The same thing can be done for your celciusToFahrenheit method.
There shouldn't be an issue performing multiple math operations on one line as long as you remember the order of operations.
You can use an example like this https://www.programmingsimplified.com/java/source-code/java-program-to-convert-fahrenheit-to-celsius
And replace Scanner with your value.
import java.util.*;
class FahrenheitToCelsius {
public static void main(String[] args) {
float temperature;
Scanner in = new Scanner(System.in);
System.out.println("Enter temperature in Fahrenheit");
temperature = in.nextInt();
temperature = ((temperature - 32)*5)/9;
System.out.println("temperature in Celsius = " + temperature);
}
}
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
I am receiving errors during compilation. It's expecting a .class. I don't think it should require one. I'm pretty new at coding so forgive my ignorance. I also would like some guidance on how to nullify Case when the user inputs C or F so they can put c or f and not get an error messages.
This is my code:
import java.util.Scanner;
import java.util.InputMismatchException;
public class TempCALC
{
public static void main(String[] args)
{
System.out.println("This Program will allow the user to calculate temperature.");
calculateTemp();
}
private static void calculateTemp() {
int F;
int C;
F=0;
C=1;
Scanner input = new Scanner (System.in);
System.out.println("Please enter a F to convert Fahrenheit to Celsius.");
System.out.println("Please enter a C to convert Celsius to Fahrenheit.");
int option = input.nextInt();
if (int=0) {
System.out.println("Please enter a temperature in degrees Fahrenheit.");
ftoc();
} else if (int= 1) {
System.out.println("Please enter a temperature in degrees Celsius.");
ctof();
} else {
System.out.println("ERROR PLEASE ENTER A F OR A C TO PROCEED!");
}
}
private static void ftoc() {
Scanner input = new Scanner(System.in);
Double celsius = input.nextDouble();
System.out.println(celsius + "celsius is" + ((celsius * 9 / 5.0) + 32) + "Fahrenheite");
calculatetemp();
}
private static void ctof() {
Scanner input = new Scanner(System.in);
Double Fahrenheit = input.nextDouble();
System.out.println(Fahrenheit + "Fahrenheit is" + ((Fahrenheit - 32) * (5 / 9.0)) + "Celsius");
calculatetemp();
}
private static void print(String string); {
System.out.println("\n" + string);
}
}
if (int=0)
This is not valid Java syntax. int is a type not a variable. You meant to write:
if(option == 0)
Notice the == (comparison) instead of = (assignment).
This is the flow you meant to implement:
if (option == 0) {
System.out.println("Please enter a temperature in degrees Fahrenheit.");
ftoc();
} else if (option == 1) {
System.out.println("Please enter a temperature in degrees Celsius.");
ctof();
} else {
System.out.println("ERROR PLEASE ENTER A F OR A C TO PROCEED!");
}
If you wish for the user to enter f or c instead to mention the degrees, you will need to use:
String option = input.next();
To get a String instead of an Integer.
And then:
if (option.equals('F') { ... }
else if(option.equals('C') { ... }
else { ... }
If you want your input to be case-insensitive take a look at toLowerCase or toUpperCase and apply it to your needs (there is an answer here that shows its use).
int is reserved key word in java you can not used it with expression to compare,you should use his value like this:
int option = input.nextInt();
if (option ==0) {
Not if (int=0) { and = is used to assign but == is used to check equality.
You first have to check the validation in your ifs statements, as the previous answers mentioned.
Also, I think that your actual conversion formulas are swapped.
Then, in order to receive either 'C' or 'c':
Read a String, instead of an int:
String option = input.next();
And then convert all the input to lowercase:
if (option.toLowerCase().equals("f"))
Here is the complete example:
public class TempCALC {
public static void main(String[] args) {
System.out.println("This Program will allow the user to calculate temperature.");
calculateTemp();
}
private static void calculateTemp() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a F to convert Fahrenheit to Celsius.");
System.out.println("Please enter a C to convert Celsius to Fahrenheit.");
String option = input.next();
if (option.toLowerCase().equals("f")){
System.out.println("Please enter a temperature in degrees Fahrenheit.");
ftoc();
}else if (option.toLowerCase().equals("c")){
System.out.println("Please enter a temperature in degrees Celsius.");
ctof();
}else{
System.out.println("ERROR PLEASE ENTER A F OR A C TO PROCEED!");
}
}
private static void ftoc() {
Scanner input = new Scanner(System.in);
Double celsius = input.nextDouble();
System.out.println(celsius + "celsius is" + ((celsius * 9 / 5.0) + 32) + "Fahrenheite");
calculatetemp();
}
private static void ctof() {
Scanner input = new Scanner(System.in);
Double Fahrenheit = input.nextDouble();
System.out.println(Fahrenheit + "Fahrenheit is" + ((Fahrenheit - 32) * (5 / 9.0)) + "Celsius");
calculatetemp();
}
private static void print(String string){
System.out.println("\n" + string);
}
private static void calculatetemp(){
System.out.println("\nInside calculateTemp");
}
}
Could someone please explain to me how to make a program with a tester class with this code as its base that will help me do this?
//This program converts the user input from Celsius to Fahrenheit and vice versa
import java.io.*;
class Converter
{
// variables
String input;
double fahrenheit;
double celcius;
//constructor with 3 parameters to initialize the variables
Converter(String converterInput, double converterFahrenheit, double converterCelcius) throws IOException
{
InputStreamReader inStream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(inStream);
input = converterInput;
fahrenheit = converterFahrenheit;
celcius = converterCelcius;
input = stdin.readLine();
fahrenheit = Double.parseDouble(input);
input = stdin.readLine();
celcius = Double.parseDouble(input);
}
// method
double fahrenheitConverter()
{
return fahrenheit = (9.0 / 5.0) * celcius + 32;
}
// method2
double celciusConverter()
{
return celcius = (5.0 / 9.0) * (fahrenheit - 32);
}
}
Sorry but this was a mess. :)
Or maybe I didnt had enough time to anticipate the way you wanted to do this.
Anyways I had to change the whole thing.I apologise for this.
Here is a code that works.
import java.io.*;
import java.util.Scanner;
final class Converter
{
// variables
double input;
double fahrenheit;
double celcius;
//constructor with 3 parameters to initialize the variables
Converter() throws IOException
{
//InputStreamReader inStream = new InputStreamReader(System.in);
String temp;
System.out.print("Please enter the temperature : ");
Scanner key=new Scanner(System.in);
input = key.nextDouble();
System.out.print("The number you gave is ");
fahrenheit=(fahrenheitConverter(input));
System.out.print(fahrenheit + " fahreneit degree , if u entered a celcious value.\n");
celcius=(celciusConverter(input));
System.out.print("Or it is "+ celcius + " celcius degree , if u entered a celcious value.\n");
}
// method
double fahrenheitConverter(double inp)
{
double iput=inp;
double fah;
fah = (iput*1.8)+ 32;
return fah;
}
// method2
double celciusConverter(double inp)
{
double iput=inp;
double cel;
cel=(iput-32)*0.5555;
return cel;
}
public static void main(String[] args) throws IOException {
Converter x=new Converter();
}
}
BUT this is only the code , in the proper (in my view) order.
Program needs to take two information items.Value and metric.
I mean that you have to ask user for the temperature (a double number) and
what is this number , celcius or fahre.
Also you will need some defence , throwing exceptions for ex. like input errors (ex user inputs like , 32,5 , a13 , 2')
Also , I used main() in order to use it compact and take the results easy.
You could have the class and call
public static void main(String[] args) throws IOException {
Converter x=new Converter();
}
from outside the class.
I will be happy to give any help beyond this.
You need to have the user specify which way they want to convert. The program doesn't do anything if the user tells the program what the Celsius and Fahrenheit temperatures already are, and you need to create methods to separately convert from Celsius to Fahrenheit and vice versa.