Is it possible to call a method using Scanner? - java

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.

Related

Java throwing exception for "No line found" when attempting to gather input from Scanner object

I am fairly new to Java and am attempting to build a "Top 10 Java Projects for Beginners" project, more specifically, a temperature converter. My code throws the following error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at TempConvert.convertToFar(TempConvert.java:78)
at TempConvert.main(TempConvert.java:15)
I was originally using the scanner "*.nextDouble()" method to grab the double but changed it to the "parseDouble" method as I thought this was perhaps the issue. Alas, this has not helped. Any help resolving this would be greatly appreciated!
public static double convertToFar()
{
Scanner in = new Scanner(System.in);
String userEntry;
double formula, userDouble;
System.out.print("Enter degrees in Celsius: ");
userEntry = in.nextLine();
userDouble = Double.parseDouble(userEntry);
in.close();
formula = (userDouble - 32) * (5/9);
return formula;
}
I think that the in.nextLine() in the methods you wrote eventually collided with the string that was inputted by the user before the input stream had been closed.
I created one Scanner object and sent it to the methods so that they will be able to use that same object. I close it only when the program ends once the user enters 'E'. It worked for me:
import java.util.*;
public class TempConvert {
public static void main(String[] args)
{
double far, cel;
char userChoice;
Scanner in = new Scanner(System.in); // I added this line
userChoice = displayMenu(in);
while (userChoice != 'E')
{
if (userChoice == 'F')
{
far = convertToFar(in);
System.out.println("Converted: " + far + "\u00B0");
userChoice = displayMenu(in);
}
else if (userChoice == 'C')
{
cel = convertToCel(in);
System.out.println("Converted: " + cel + "\u00B0");
userChoice = displayMenu(in);
}
else
{
System.out.println("Invalid Entry");
userChoice = displayMenu(in);
}
}
in.close(); // closing the input stream when the program ends
}
public static void displayTitle()
{
String title = "||---- TEMPERATURE CONVERTER ----||";
String one = "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-";
String two = "|| ** Auth: Arranic ||";
String three = "|| ||";
System.out.println(one + "\n" + three + "\n" + title + "\n" + three + "\n" + two + "\n" + three + "\n" + one);
}
public static char displayMenu(Scanner input)
{
ClearScreen();
displayTitle();
System.out.println("\n");
String choiceString;
char choice;
System.out.println("F - FARENHEIGHT C - CELSIUS E - EXIT");
System.out.print("CONVERT TO: ");
choiceString = input.nextLine();
// input.close() --> removed this line
choice = Character.toUpperCase(choiceString.charAt(0));
return choice;
}
public static void ClearScreen()
{
System.out.print("\033[H\033[2J");
System.out.flush();
}
public static double convertToCel(Scanner in)
{
String userEntry;
double formula, userDouble;
System.out.print("Enter degrees in Fahrenheit: ");
userEntry = in.nextLine();
// in.close() --> removed this line
userDouble = Double.parseDouble(userEntry);
formula = (userDouble - 32) * (5.0/9);
return formula;
}
public static double convertToFar(Scanner in)
{
String userEntry;
double userDouble, formula;
System.out.print("Enter degrees in Celsius: ");
userEntry = in.nextLine();
// in.close() --> removed this line
userDouble = Double.parseDouble(userEntry);
formula = (userDouble * (9.0/5)) + 32;
return formula;
}
}
BTW your calculations are not precise. You should remember that integer/integer = integer. That said, writing 5/9 or 9/5 is not accurate, since the result is an integer type number, and not a double type number, as I assume you wanted to get. (5/9 = 0, 9/5 = 1) So you should have added a 5.0 or 9.0 to the calculations so that Java would understand that you want to get a double type result (double/int = double).
And one more thing, your calculations where misplaced (fahrenheit to celsius gave me the opposite result and vice versa) so I switched them up ;).

I'm getting weird loop behaviour after passing char instead int

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.

thermometer class logic error

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

Temperature Calculator for Java

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");
}
}

Java OOP Temperature Converter

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());
}
}

Categories

Resources