I'm just starting on Java and I came across some problems:
I'm trying to make a program to convert Celsius to Farenheit
I can't use the variable c from the first object on my second class. Why?
I would like to know how can I ask the user to input wether they would like to convert it to Celsius or Farenheit, using a BufferedReader object and a try-catch statement.
Class temperatura {
private double tempF, tempC;
public void setFarenheit(double f) {
tempF = f;
}
public void setCelsius(double c) {
tempC = c;
}
// Convierte de grados C a grados F
public double celsiusToFarenheit() {
return (1.8*tempC)+32;
}
// Convierte de grados F a grados C
public double farenheitToCelsius() {
return (tempF-32)/1.8;
}
}
class TemperaturaPrueba {
public static void main(String[] args) {
Temperatura convTemp;
convTemp = new Temperatura();
convTemp.setCelsius(100);
convTemp.setFarenheit(212);
System.out.println(c + " grados Celsius son " +
convTemp.celsiusToFarenheit() + " grados Farenheit");
System.out.println(f + " grados Farenheit son " +
convTemp.farenheitToCelsius() + " grados Celsius");
}
}
I can't use the variable c from the first object on my second class. Why?
Yes, it has to do with the variable scopes. The tempC variable you are referring to is not present in your main method (see the image). But your main method has the reference to Temperatura object in the heap. So, you could add a getter method
like
public double getCelsius(){
return tempC;
}
to the Temperature class and get the value in your main method and use it.
convTemp.getCelsius();
I would like to know how can I ask the user to input wether they would like to convert it to Celsius or Farenheit, using a BufferedReader object and a try-catch statement.
And for this question, a simple google search will help you. Some links: https://www.tutorialspoint.com/how-to-read-integers-from-a-file-using-bufferedreader-in-java
sample:
boolean isValidInput = false;
do {
try{
BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter celsius: ");
int celsius = Integer.parseInt(reader.readLine());
isValidInput = true;
} catch(Exception e){
System.out.println("Invalid input, please try again");
}
} while(!isValidInput);
You have to either make tempC and tempF a public field or you have to write getter methods.
Class temperatura {
public double tempF, tempC; /* I have made these fields public */
public void setFarenheit(double f) {
tempF = f;
}
public void setCelsius(double c) {
tempC = c;
}
// Convierte de grados C a grados F
public double celsiusToFarenheit() {
return (1.8*tempC)+32;
}
// Convierte de grados F a grados C
public double farenheitToCelsius() {
return (tempF-32)/1.8;
}
}
class TemperaturaPrueba {
public static void main(String[] args) {
Temperatura convTemp;
convTemp = new Temperatura();
convTemp.setCelsius(100);
convTemp.setFarenheit(212);
//Note that I have changed the c and f references to actual field names
System.out.println(convTemp.tempC + " grados Celsius son " +
convTemp.celsiusToFarenheit() + " grados Farenheit");
System.out.println(convTemp.tempF + " grados Farenheit son " +
convTemp.farenheitToCelsius() + " grados Celsius");
}
}
From Your code the variable 'c' & 'f' you are using in class temperatura are local so variables which are used as parameters so their access scope is limited within the function.
Instead of that you can use the variables tempF, tempC with object of class temperatura
also for your second question you want to get user's choice you can use Scanner or other input method after taking user choice you can use switch statement to call your functions
here the code how you can do it
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Your Choice");
System.out.println("1.F to c \n2.c to f");
String choice = sc.nextLine();//Read User Input
switch(choice) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
}
}
This is not actual code but this is the format you needed to run your project
Related
I am new to java and I'm working on a temp conversion tool
the whatToDo method takes a users input and runs it though if and else if statements and will convert one unit to another depending on what the user imputed
then the whatsNext method runs once the conversion method was executed it will ask the user if they want to convert something else convert the same thing or exit the program
I want it so when the whatsNext method is ran the and the user inputs "1" it will run the same conversion method that was just run from the whatToDo method
I have tried to take the WhatToConvert int from the whatToDo method to make a new if statement in the whatsNext method but I can not because its in a method and java cannot find it
Thank you in advanced if you do help :)
import java.util.Scanner;
public class App {
public static void conversions() {
System.out.println("What two temperatures would you like to convert?");
System.out.println("[1]:celsius to fahrenheit");
System.out.println("[2]:fahrenheit to celsius");
System.out.println("[3]:celsius to kelvin");
System.out.println("[4]:fahrenheit to kelvin");
System.out.println("[5]:kelvin to celsius");
System.out.println("[6]:kelvin to fahrenheit");
}
public static void options() {
System.out.println("what would you like to do now?");
System.out.println("[1]:convert the same thing");
System.out.println("[2]:convert something else");
System.out.println("[3]:exit");
}
public static void whatToDo() {
Scanner in = new Scanner(System.in);
conversions();
int whatToConvert = in.nextInt();
if (whatToConvert == 1) {
cF();
} else if (whatToConvert == 2) {
fC();
} else if (whatToConvert == 3) {
cK();
} else if (whatToConvert == 4) {
fK();
} else if (whatToConvert == 5) {
kC();
} else if (whatToConvert == 6) {
kF();
}
else {
System.out.flush();
System.out.println(whatToConvert + ": is a unknown command pls try again:");
whatToDo();
}
}
// runs once conversion method was run
public static void whatNext() {
var in = new Scanner(System.in);
options();
int choice = in.nextInt();
if (choice == 1) {
System.out.println("needs to be added");
cF();
} else if (choice == 2) {
whatToDo();
} else if (choice == 3) {
System.exit(1);
}
}
// conversion methods
public static void cF() {
Scanner in = new Scanner(System.in);
System.out.println("please enter the temperature in celsius:");
double cToF = in.nextDouble();
System.out.println(cToF + "°C is about " + (cToF * 1.8 + 32) + "°F");
}
public static void fC() {
Scanner in = new Scanner(System.in);
System.out.println("please enter the temperature in fahrenheit:");
double fToC = in.nextDouble();
System.out.println(fToC + "°F is about " + (fToC - 32) / 1.8 + "°C");
}
public static void cK() {
Scanner in = new Scanner(System.in);
System.out.println("enter the temperature in celsius:");
double cToK = in.nextDouble();
System.out.println(cToK + "°C is about " + (cToK + 273.15) + "°K");
}
public static void fK() {
Scanner in = new Scanner(System.in);
System.out.println("enter the temperature in fahrenheit:");
double fToK = in.nextDouble();
System.out.println(fToK + "°F is about " + ((fToK - 32)*5/9 + 273.15) + "°K");
}
public static void kC() {
Scanner in = new Scanner(System.in);
System.out.println("enter the temperature in kelvin:");
double kToC = in.nextDouble();
System.out.println(kToC + "°K is about " + (kToC - 273.15) + "°C");
}
public static void kF() {
Scanner in = new Scanner(System.in);
System.out.println("enter the temperature in kelvin:");
double kToF = in.nextDouble();
System.out.println(kToF + "°K is about " + ((kToF - 273.15)* 9/5 + 32) + "°C");
}
public static void main(String[] args) throws Exception {
while (true) {
whatToDo();
whatNext();
}
}
}
I could think of two easy ways you can achieve this:
The variable whatToConvert is declared inside a variable. Hence its scope (or simply say its access) is only inside that method - unless you specifically pass it as argument to some other method.You can also have variables with global scope - meaning variables declared at class level and not inside a method. Such variables are accessible to all the methods of that class.You can read more on "scope of variables in java".
What you can do here is - declare whatToConvert variable as static at class level instead of inside whatToDo() method.
public class App {
static int whatToConvert = 0;
//all other code
}
Method whatNext() can then have access to this variable.
You know that whatNext() always runs after whatToDo(). In such case, you can return the value of 'whatToConvert' from whatToDo() and pass
that value as method argument to whatNext()
In either case you should extract the if-else code to a new method to add re-usability for method whatNext()
New method can have method signature something like:
public static void decideOperation(int choice) {
//If-else blocks or switch case
}
When you declare a variable in a method, it will be local, so it will be instantiated and in the method and removed once the method is finished. In order for a variable to be read by all methods you should declare it as a global variable, in this way:
public class App {
private static int whatToConvert;
...
public static void whatToDo() {
Scanner in = new Scanner(System.in);
conversions();
whatToConvert = in.nextInt();
...
}
Now you can use whatToConvert in other methods
I'm working on a JavaRush Course problem - <Fahrenheit/Celsius Converter>:
Ask user direction of conversion
Ask user a temperature
Convert and print out result temperature
I'm trying to break program on a separate methods to understand how to work with methods and how to pass variables (I'm beginner in programing)
this is my code:
import java.util.Scanner;
public class FahrenheitCelsius {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("---< Fahrenheit / Celsius Converter >---");
String direction = getDirection();
int temperature = getTemperature(direction);
getResult(direction, temperature);
sc.close();
}
// let's get direction of conversion from user input
static String getDirection() {
String direction;
do {
System.out.print("Convert from F or C: ");
direction = sc.nextLine();
} while (!direction.equals("F") && !direction.equals("C"));
return direction;
}
// let's get temperature from user
static int getTemperature(String direction) {
int temperature;
System.out.print("temperature in " + direction + ": ");
while (!sc.hasNextInt()) {
System.out.print("temperature in " + direction + ": ");
sc.nextLine();
}
temperature = sc.nextInt();
return temperature;
}
// let's convert Fahrenheit to Celsius
static int fahrenheitToCelsius(int temperatureF) {
return (temperatureF - 32) * 5 / 9;
}
// let's convert Celsius to Fahrenheit
static int celsiusToFahrenheit(int temperatureC) {
return temperatureC * 9 / 5 + 32;
}
// let's get result using direction and temperature we got
static void getResult(String direction, int temperature) {
int result;
if (direction.equals("F")) {
result = fahrenheitToCelsius(temperature);
System.out.println("result temperature: " + result + "C");
} else {
result = celsiusToFahrenheit(temperature);
System.out.println("result temperature: " + result + "F");
}
}
}
But!!!
I'm trying to write getTemperature method using do while loop.
Like this:
static int getTemperature(String direction) {
int temperature;
do {
System.out.print("temperature in " + direction + ": ");
sc.nextInt();
} while (!sc.hasNextInt());
temperature = sc.nextInt();
return temperature;
}
At first I used separate instances of Scanner inside each method. And I got noSuchElementExeption - if user unput characters
Then I got the idea that I dont have to close scanner in getDirection method.
Then I red some advices in Stackoverflow and created separate static final instance of Scanner and passed it into methods
And right now I'm getting - infinite loop if user types characters instead integers
I know that is some weird behaviour with Scanner and this nextLine() thing.
But can't get an idea how to make getTemperature using do while loop without this bug.
Thanks in advance guys.)
Your main() method might contain:
System.out.println("---< Fahrenheit / Celsius Converter >---");
String direction = "";
// Use of the String#matches() method with a small Regular Expression.
// (?i) Ignore Letter Case
// [FC] Only allow the character q, or Q
while (!direction.matches("(?i)[q]")) {
direction = getDirection();
if (!direction.matches("(?i)[q]")) {
int temperature = getTemperature(direction);
printResult(direction, temperature);
}
System.out.println();
}
The getDirection() method might look like:
// let's get direction of conversion from user input
public static String getDirection() {
String direction = "";
while (direction.isEmpty()) {
System.out.println("Enter temperature scale to convert:");
System.out.println(" F) Fahrenheit");
System.out.println(" C) Celsius");
System.out.println(" Q) Quit");
System.out.print("Your choice: --> ");
direction = sc.nextLine();
if (direction.equalsIgnoreCase("q")) {
System.out.println("\nBye-Bye\n");
break;
}
// Use of the String#matches() method with a small Regular Expression.
// (?i) Ignore Letter Case
// [FC] Only allow the characters F, f, C, or c (q is handled ahead of time)
if (!direction.matches("(?i)[FC]")) {
System.err.println("Invalid Temperature Scale Type (" + direction
+ ")! Must be F or C! Try again...\n");
direction = "";
}
}
return direction;
}
The getTemperature() method might look like:
// let's get temperature from user
private static int getTemperature(String direction) {
String temp = "";
// 'Ternary Operators' used here
String directString = (direction.equalsIgnoreCase("f") ? "Fahrenheit" : "Celsius");
String otherDirectString = (direction.equalsIgnoreCase("f") ? "Celsius" : "Fahrenheit");
System.out.println();
System.out.println("Convert a Temperature in " + directString + " to " + otherDirectString + ":");
do {
System.out.print("Enter a temperature in " + directString + ": --> ");
temp = sc.nextLine().trim();
// Since you're working with integer for temperature...
// Use of the String#matches() method with a small Regular Expression.
// ("\\d+") Must be a string representation of an Integer numerical
// value with 1 (or possibly) more digits.
if (!temp.matches("\\d+")) {
System.err.println("Invalid Temperature Supplied (" + temp + ")! Try Again..." );
temp = "";
}
} while (temp.isEmpty());
return Integer.valueOf(temp);
}
The getResult() name is changed to printResult() because that is all it is essentially doing. It's not really getting anything:
// let's get result using direction and temperature we got
static void printResult(String direction, int temperature) {
// 'Ternary Operator' used here
System.out.println("Converted temperature is : "
+ (direction.toUpperCase().equals("F")
? fahrenheitToCelsius(temperature) + "C"
: celsiusToFahrenheit(temperature) + "F"));
}
Other misc. methods remain the same:
// let's convert Fahrenheit to Celsius
public static int fahrenheitToCelsius(int temperatureF) {
return (temperatureF - 32) * 5 / 9;
}
// let's convert Celsius to Fahrenheit
public static int celsiusToFahrenheit(int temperatureC) {
return temperatureC * 9 / 5 + 32;
}
Read the comments in code. You will of course notice that there is use of the String#matches() method for validation along with various small Regular Expressions which are explained in the comments.
You will also notice the use of Ternary Operators to reduce the display of IF/ELSE statements.
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 found some code online to make my own little project as I want to learn Java on my spare time, I found some broken code and tried fixing it myself to the best of my ability, but now I got stuck.
The error I'm receiving is:
TempProg.java:53: error: cannot find symbol
Temperature tempConv = new Temperature();
^
symbol: class Temperature
location: class TempProg
TempProg.java:53: error: cannot find symbol
Temperature tempConv = new Temperature();
^
symbol: class Temperature
location: class TempProg
2 errors
import java.util.Scanner;
public class TempProg {
public double currentTemp;
public double TempF;
public double TempK;
public double newTemp;
public TempProg(double startCurrentTemp, double startTempF, double startTempK, double startnewTemp)
{
currentTemp = startCurrentTemp;
TempF = startTempF;
TempK = startTempK;
newTemp = startnewTemp;
}
private double Temperature(double currentTemp)
{
currentTemp = 100;
return currentTemp;
}
public double convertToF(double TempF, double currentTemp)
{
TempF = ((9 * currentTemp) / 5 ) + 32;
return TempF;
}
public double convertToK(double TempK, double currentTemp)
{
TempK = currentTemp + 273;
return TempK;
}
public double updateTempC(double currentTemp)
{
newTemp = currentTemp;
return currentTemp;
}
public double getTemp()
{
return currentTemp;
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Temperature tempConv = new Temperature();
int newTemp;
boolean entryValid;
final int MIN_TEMP = -273;
final int MAX_TEMP = 10000;
System.out.println("\tTemperature converter");
char selection = 'x';
while (selection != 'q') {
System.out.println("\n\tCurrent temperature in degrees C: " + tempConv.getTemp());
System.out.println("\tType f to display temperature in Fahrenheit");
System.out.println("\tType k to display temperature in Kelvin");
System.out.println("\tType c to set a new temperature");
System.out.println("\tType q to quit");
selection = scan.next().charAt(0);
switch(selection) {
case 'f':
System.out.println("\n\t" +tempConv.getTemp()+ " degrees C = "+tempConv.convertToF() +" degrees F" );
break;
case 'k':
System.out.println("\n\t" +tempConv.getTemp()+ " degrees C = "+tempConv.convertToK() +" degrees K" );
break;
case 'c':
entryValid=false;
while (!entryValid) {
System.out.print("\n\tPlease enter a new temperature: ");
newTemp = scan.nextInt();
if (newTemp < MIN_TEMP || newTemp > MAX_TEMP) {
System.out.println("\tPlease enter a valid temperature");
} else {
entryValid=true;
tempConv.updateTempC(newTemp);
}
}
break;
case 'q':
break;
default:
System.out.println("\n\tOption " + selection + " not understood");
}
}
}
}
At line 53, you are trying to create a new Temperature object with the following call:
Temperature tempConv = new Temperature();
The new operator in Java means that you are creating a new Object of the type specified after the new variable.
In order to create a new instance of a new Object, you must either have that class in the same package as the code that is creating the new instance or you must import the class.
The fact that you are getting the cannot find symbol error means that the compiler cannot find that class so it is not in the same package and it is not imported.
Normally, the fix for this is to import the class if it has already been created and it is in some other class. If this is code you are creating, you may need to create the Temperature object.
Later in your code, you have the following method:
private double Temperature(double currentTemp)
{
currentTemp = 100;
return currentTemp;
}
This creates a method called Temperature, but it does not create a Temperature object. This can be confusing. In Java, to avoid this confusion, method names should always start with lowerCase letters and classes should always start with UpperCase.
You are getting the error because you are trying to create new object by using method name.
new ClassName() is used for creating the object of that class. new keyword is used with the class name not with the method name. For calling the method first you have to create the object of that class and than with the help of that object you can call the method. In your TempProg class you don't have a default constructor you should write one default constructor if you want to create obj to TempProg without setting any value for your member variable like currentTemp,.....
In your case you should do like -
TempProg()
{}
TempProg tempObj = new TempProg(); //than you can create the obj of TempProg like that
if you want to use parameterized constructor than you have to do like
TempProg tempObj = new TempPRog(11.2,222,453,455); //whatever vallue you want to set for those variables
tempObj.Temperature(1122); // call the Temperature method by passing value.
I am just putting some value as a example in this post.
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());
}
}