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);
}
}
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.
Hello I'm working on a project for my java class, I'm supposed to write a code for a Algebra tutor that goes like this:
Write a program with a that displays a randomly generated problem that asks the user to solve for the y variable, takes input from the user, and prints "correct" if the user answered correctly and prints "incorrect" if not. Your main should give one problem and then exit. Use one or more methods to produce this behavior.
This is regarding the formula mx + b. So here is what I have so far, and works!
import java.util.Random;
import java.lang.Math;
import java.util.Scanner;
class Main {
public static void main(String[] arg){
double min_value = -100;
double max_value = 100;
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int)m_value * (int)x_value + (int)b_value;
if (user_answer.equals(correct_answer))
System.out.println("You are correct!");
else
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
}
}
so even tho the output is correct, I need to break down the code into smaller methods, this is where Im getting confused on how to take a piece of that code and put it in another method that once it runs it calls for that method too and gives me the same output. I been ready the material given but the more I read it the more confuse I get. If anybody has any ideas or suggestions please let me know any info will be really appreciate. Thank you
Here's a quick rundown on methods, so it's not completely done yet. Ask, if you need more help! Good luck on your homework and on becoming one of the beast developers!
public class Main {
public static void main(String[] args) {
int a = 1; // give a value of 1
methodTwo(a); // sending the int a into another method
}
// Here's method number two
static void methodTwo (int a) { // it gives a's type and value
System.out.println(a); //Gives out a's value, which is 1
}
}
Technically you've solved the problem correctly, you are using one or more methods, but perhaps what you trying to do is a common code refactor called the extract method / extract function refactor Executing this type of refactor leads to much more readable and maintainable code, and is easy to do.
As a starter, identify code that repeats or looks similar, in your case, the following lines look ripe for extract method:
double m_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double x_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
double b_value = (int)(Math.random()*((max_value-min_value)+1))+min_value;
Notice that the RHS of each line is identicial, so we can replace the explicit code with a method call like this:
double m_value = getRandomDoubleBetween(max_value, min_value);
double x_value = getRandomDoubleBetween(max_value, min_value);
double b_value = getRandomDoubleBetween(max_value, min_value);
private double getRandomDoubleBetween(double max_value, double min_value) {
return (int)(Math.random()*((max_value-min_value)+1))+min_value;
}
You can identify other areas of code that either contain repetition or perhaps some hard to understand code that would be more understandable if it was extracted into a method that had a name that reveals what the code is doing.
Please review this, you are comparing string with integer,
if (user_answer.equals(correct_answer))
This may help you:
import java.util.Scanner;
class Main {
public static void main(String[] arg) {
double min_value = -100;
double max_value = 100;
double m_value = generateRandom(max_value, min_value);
double x_value = generateRandom(max_value, min_value);
double b_value = generateRandom(max_value, min_value);
System.out.println("Given: ");
System.out.println("m = " + m_value);
System.out.println("x = " + x_value);
System.out.println("b = " + b_value);
checkAnswer(m_value, x_value, b_value);
}
private static void checkAnswer(double m_value, double x_value, double b_value) {
System.out.print("What is the value of y? ");
Scanner user_input = new Scanner(System.in);
String user_answer = "";
user_answer = user_input.next();
int correct_answer = (int) m_value * (int) x_value + (int) b_value;
if (user_answer.equals(String.valueOf(correct_answer))) {
System.out.println("You are correct!");
} else {
System.out.print("Sorry, that is incorrect. ");
System.out.println("The answer is " + correct_answer);
user_input.close();
}
}
static int generateRandom(double max_value, double min_value) {
return (int) ((int) (Math.random() * ((max_value - min_value)
+ 1)) + min_value);
}
}
i thought the for loop would loop in the method and return the double until it ended but it only does the process once and outputs the one number over and over till its done
public class CtoFTableDisplay {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String string1 = "°C";
String string2 = "°F";
double Celsius2 = -100;
double fahrenheit = 0;
fahrenheit = CtoF(Celsius2);
//double fahrenheit = CtoF(Celsius2);
System.out.format("%5s%9s", string1, string2);
for (Celsius2 = -100; Celsius2 <= 100; Celsius2++) {
System.out.format ("\n%3.1f%9.1f", Celsius2, fahrenheit);
System.out.println();
}
}
public static double CtoF(double Celsius) {
double [] ans = new double [200];
double fahrenheit = 0;
for (Celsius = -100; Celsius <= 100; Celsius++) {
fahrenheit = (Celsius * 9/5) + 32;
}
return fahrenheit;
}
}
Change the loop to be this:
for (Celsius2 = -100; Celsius2 <= 100; Celsius2++) {
System.out.format ("\n%3.1f%9.1f", Celsius2, fahrenheit);
fahrenheit = CtoF(Celsius2);
System.out.println();
}
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());
}
}
I am a complete beginner and hardly even know the basics of Java (I've only been in the class for two weeks). My first assignment is to calculate the heat index based on the current temperature and current humidity given by the user, in java using Eclipse. I have come up with a code, however, to no avail. My code does ask users to input the temperature and humidity, but it does not print out the results. I provided the UML diagram I was required to use to build the code that way you have a better understanding of why I did what I did. Ultimately, I think my problem lies somewhere in the process of passing values to and from different methods... Is there anyone who would be willing to take a look and possibly guide me in the right direction?
import java.util.Scanner;
public class HeatIndexCalculator1 {
private int temperature;
private double humidity;
private double heatIndex;
public static void main(String args[]) {
//Get current temp and humidity from user
Scanner input = new Scanner(System.in);
System.out.printf("Please enter the current temperature in degrees Fahrenheit: ");
int currentTemp = input.nextInt();
System.out.printf("\nPlease enter the current humidity as a percentage: ");
double currentHumidity = input.nextDouble();
}
private double calculateHeatIndex ( int currentTemp, double currentHumidity ) {
//Setting parameters for Function
int temperature = currentTemp;
double humidity = currentHumidity;
double answer;
final double C1 = -42.379;
final double C2 = 2.04901523;
final double C3 = 10.14333127;
final double C4 = -0.22475541;
final double C5 = -.00683783;
final double C6 = -5.481717E-2;
final double C7 = 1.22874E-3;
final double C8 = 8.5282E-4;
final double C9 = -1.99E-6;
int T = temperature;
double R = humidity;
double T2 = temperature * temperature;
double R2 = humidity * humidity;
//Function of Calculating Heat Index
double answer = C1 + (C2 * T) + (C3 * R) + (C4 * T * R) + (C5 * T2) + (C6 * R2) + (C7 * T2 * R) + (C8 * T * R2) + (C9 * T2 * R2);
return answer;
}
private void printHeatIndex( int currentTemp, double currentHumidity, double calculatedHeatIndex) {
double calculatedHeatIndex = answer;
//Print Heat Index
System.out.println("\nAt a temperature of" + currentTemp + "and a humidity of" + currentHumidity + "percent . . .\n");
System.out.println("\nIt feels like:" + calculatedHeatIndex + "F");
}
}
You need to change your main method as per below:
public static void main(String args[]) {
//Get current temp and humidity from user
Scanner input = new Scanner(System.in);
System.out.printf("Please enter the current temperature in degrees fahrenheit: ");
int currentTemp = input.nextInt();
System.out.printf("\nPlease enter the current humidity as a percentage: ");
double currentHumidity = input.nextDouble();
//Creating object of HeatIndexCalculator class
HeatIndexCalculator1 heatIndex = new HeatIndexCalculator1();
double x = heatIndex.calculateHeatIndex(..,..);
heatIndex.printHeatIndex(currentTemp,currentHumidity,x);
}
Also, compiler may give your error because the methods in HeatIndexCalculator1 class are private, if you change them to public it works.