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.
Related
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
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.
So, I have a variable in a parent class that I am trying to change in a subclass with getter/setter methods. But, the value is just staying the same and I have no idea why.. What am I doing wrong? Any help is appreciated!
Here is a breakdown of the program: In the driver class, you choose what you want to do, then it uses the current value variable and a number you choose (operand2) to get the answer. The add, subtract, multiply and divide are in the memory calculator class. It can also clear, which sets the current value variable to zero. Now, we are adding a sub class to it that does exponents and logarithms.
specifics: The variable currentValue in the MemoryCalc class stays the same when I try to use the power or log methods in the ScientificMemCalc class. In that class it uses a getter method to get the current value and then attempts to use a setter method to change the current value. But nothing changes. And another problem: the getter method gets a zero value from the currentValue field.
Here is driver class with main method:
package ScientificMemCalc;
import java.util.Scanner;
import ScientificMemCalc.MemoryCalc;
public class ScientificCalcDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
MemoryCalc calculator = new MemoryCalc();
ScientificMemCalc scientificCalc = new ScientificMemCalc();
int menu = 0;
double operand2, answer;
while (menu !=8) {
answer = calculator.getCurrentValue();
System.out.println("The current value is: " + answer);
menu = getMenuOption();
switch(menu) {
case 1:
// Add
operand2 = calculator.getOperand("What is the second number?: ");
calculator.add(operand2);
break;
case 2:
// Subtract
operand2 = calculator.getOperand("What is the second number?: ");
calculator.subtract(operand2);
break;
case 3:
// Multiply
operand2 = calculator.getOperand("What is the second number?: ");
calculator.multiply(operand2);
break;
case 4:
// Divide
operand2 = calculator.getOperand("What is the second number?: ");
calculator.divide(operand2);
break;
case 5:
// Power
operand2 = calculator.getOperand("What is the second number?: ");
scientificCalc.power(operand2);
break;
case 6:
// Logarithm
scientificCalc.log();
break;
case 7:
// Clear
operand2 = 0;
calculator.clear();
break;
case 8:
// Quit
System.out.println("Goodbye!");
break;
}
}
}
public static int getMenuOption() {
Scanner input = new Scanner(System.in);
int choice = 0;
// Display menu
System.out.println("Menu:");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Power");
System.out.println("6. Logarithm");
System.out.println("7. Clear");
System.out.println("8. Quit");
// Get menu input
System.out.print("What would you like to do?: ");
choice = input.nextInt();
while (choice < 1 || choice > 8) {
System.out.print("Invalid. Try again: ");
choice = input.nextInt();
}
return choice;
}
}
Here is the memory calculator class:
package ScientificMemCalc;
import java.util.Scanner;
public class MemoryCalc {
private double currentValue;
public double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
System.out.print(prompt);
return input.nextDouble();
}
public double getCurrentValue() {
return currentValue;
}
public void setCurrentValue(double temp) {
currentValue = temp;
}
public void add(double operand2) {
// Add
currentValue += operand2;
}
public void subtract(double operand2) {
// Subtract
currentValue -= operand2;
}
public void multiply(double operand2) {
// Multiply
currentValue *= operand2;
}
public void divide(double operand2) {
// Divide
if (operand2 == 0) {
System.out.println("You cannot divide by zero!");
currentValue = Double.NaN;
}
else {
currentValue /= operand2;
}
}
public void clear() {
// Clear
currentValue = 0;
}
}
And finally the subclass to add scientific functions:
package ScientificMemCalc;
public class ScientificMemCalc extends MemoryCalc {
public void power(double operand2) {
// Power
double currentValue = getCurrentValue();
double temp = Math.pow(currentValue, operand2);
setCurrentValue(temp);
}
public void log() {
// Logarithm
double currentValue = getCurrentValue();
double temp = Math.log(currentValue);
setCurrentValue(temp);
}
}
Short answer
You're interacting with TWO DIFFERENT OBJECTS calculator and scientificCalc. They do not share any state.
What can you do?
Use scientificCalc for all the calculations. Thus the value will be one and only.
cons : the things can become much more complicated once you introduce another calculator types
Pass the calculator to constructor of ScientificMemCalc as a constuctor parameter.
cons : same as for #1
Use a separate class/object for storing the state. (as suggested by #user2864740)
Do not store the state inside the calculator (Why would you need that?). Pass all the operands (current state will be always operand #1) to the methods and return the result to caller:
int menu = 0;
double operand2, answer;
while (menu !=8) {
// You don't need this line
//answer = calculator.getCurrentValue();
System.out.println("The current value is: " + answer);
menu = getMenuOption();
switch(menu) {
case 1:
// Add
operand2 = calculator.getOperand("What is the second number?: ");
//
answer = calculator.add(answer, operand2);
break;
//... modify other operations in the same way
}
In the ScientificMemCalc class you extend MemoryCalc, this lets ScientificMemCalc call the methods created in MemoryCalc and provides access to its own set of variables in MemoryCalc. However, when creating two separate objects of each class, they will both have access to a variable of the same name and type, but they will be two separate variables in two separate objects.
One solution is passing in a MemoryCalc object into the constructor of the ScientificMemCalc class then calling the getCurrentValue()/setCurrentValue() methods in respects to that object. Allowing access to the same variable.
package scientificMemCalc;
public class ScientificMemCalc {
//store the MemoryCalc object so we have access to the needed data
private MemoryCalc memCalc;
//store the MemoryCalc
public ScientificMemCalc(MemoryCalc memCalc) {
this.memCalc = memCalc;
}
public void power(double operand2) {
// Power
double currentValue = memCalc.getCurrentValue();
double temp = Math.pow(currentValue, operand2);
memCalc.setCurrentValue(temp);
}
public void log() {
// Logarithm
double currentValue = memCalc.getCurrentValue();
double temp = Math.log(currentValue);
memCalc.setCurrentValue(temp);
}
}
Then when instantiating your ScientificMemCalc object pass in the reference for your MemoryCalc.
MemoryCalc calculator = new MemoryCalc();
ScientificMemCalc scientificCalc = new ScientificMemCalc(calculator);
Hope this helps!
In my class we needed to make a memory calculator in Java. Im really new to Java and had help making the program. Turned it in and the teacher said "Please separate the MemoryCalculator class from the class with the main() method. Currently the way you have created the class, there is no reason to create an instance of the class. But the point of the assignment is to use separate classes and objects." Its been a super long week and midterms and just lost at this time. Any help would be great.
import java.util.Scanner;
public class MemoryCalculator {
private double currentValue;
//Methods
//Scanner
public static int displayMenu(){
Scanner input = new Scanner(System.in);
System.out.print("Lets do some math! \nMenu \n1. Add \n2. Subtract \n3. Multiply \n4. Divide \n"
+ "5. Clear \n6. Quit \n\nWhat would you like to do? ");
int menuChoice = input.nextInt();
return menuChoice;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System. in );
double operand;
System.out.println(prompt);
operand = input.nextDouble();
return operand;
}
//Current Value
//Gets
public double getCurrentValue() {
return currentValue;
}
//Setter
public void setCurrentValue(double currentValue) {
this.currentValue = currentValue;
}
//Add
public void add(double operand2) {
currentValue += operand2;
}
//Subtract
public void subtract(double operand2) {
currentValue -= operand2;
}
//Multiply
public void multiply(double operand2) {
currentValue *= operand2;
}
//Divide
public void divide(double operand2) {
if (operand2==0){
setCurrentValue(0);
}
currentValue /=operand2;
}
//Clear
public void clear() {
currentValue = 0;
}
//Main part of the calculator
public static void main(String[] args) {
MemoryCalculator instance = new MemoryCalculator();
double operand;
boolean repeat = true;
while (repeat) {
System.out.println("The current value is: " + instance.getCurrentValue() + "\n");
int menuChoice;
menuChoice = displayMenu();
if (menuChoice > 6 || menuChoice < 1){
System.out.println("I'm sorry, " + menuChoice + " wasn't one of the options\n");
}
switch(menuChoice){
case 1:
operand = getOperand("What is the second number?");
instance.add(operand);
break;
case 2:
operand = getOperand("What is the second number?");
instance.subtract(operand);
break;
case 3:
operand = getOperand("What is the second number?");
instance.multiply(operand);
break;
case 4:
operand = getOperand("What is the second number?");
instance.divide(operand);
break;
case 5:
instance.clear();
break;
case 6:
System.out.println("Goodbye have a great day");
System.exit(0);
break;
}
}
}
}
What it looks like you did with your program was create one, single, class that holds all of the code for your calculator program, within which you instantiated an object of the same class.
What your teacher wants instead, is for you to have two separate classes, one which contains the code that makes the calculator work, and another class where you instantiate an object of the first class, and call the methods contained within that class.
For your assignment, what I would suggest would be to create a new class, perhaps called Main, where your program's Main() method will be, and keep all of the code for the calculator program in the MemoryCalculator class. From there, you can instantiate an object of MemoryCalculator class (which you already did, called instance) and use method calls to reference methods and attributes from within the MemoryCalculator class.
This may require reworking some of your code so that it runs properly, given that you'll be calling most of it from an object of the MemoryCalculator class, but it should be doable.
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());
}
}