I am new to java and i read a few chapters. Just can't figure out how to use another method in this program that converts temps from F to C and vice versa
Here is my code right now:
import java.io.*;
import javax.swing.JOptionPane;
public class Converter {
public static void main(String[] args) throws Exception{
String unit = JOptionPane.showInputDialog("Enter unit F or C: ");
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp1 = JOptionPane.showInputDialog("Enter the Temperature: ");
double temp = Double.valueOf(temp1).doubleValue();
if((unit.equals("F"))||(unit.equals("f"))){
double c= (temp - 32) / 1.8;
JOptionPane.showMessageDialog(null,c+" Celsius");
}
else if((unit.equals("C"))||(unit.equals("c"))){
double f=((9.0 / 5.0) * temp) + 32.0;
JOptionPane.showMessageDialog(null,f+" Fahrenheit");
}
}
}
You could create static methods to convert from on to another, e.g.
public static double fahrenheitToCelsius(double temp) {
return (temp - 32) / 1.8;
}
etc.
A side note: you could simplify your if clause to if(unit.equalsIgnoreCase("F")) or better if("F".equalsIgnoreCase(unit)), since that would handle unit = null as well.
One thing you can do is split the logic which converts temperature i.e.:
public static double toDegreesCelsuis(double tempF){
double c= (tempF - 32) / 1.8;
return c;
}
public static double toFahrenheit(double tempC){
double f=((9.0 / 5.0) * tempC) + 32.0;
return f;
}
These can then be called in your main method like:
double c = Converter.toDegreesCelsuis(40.0);
Here it is,
public class Converter {
public static void main(String[] args) throws Exception{
String unit = JOptionPane.showInputDialog("Enter unit F or C: ");
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp1 = JOptionPane.showInputDialog("Enter the Temperature: ");
double temp = Double.valueOf(temp1).doubleValue();
double f = getTemprature(temp, unit);
JOptionPane.showMessageDialog(null,f+" Fahrenheit");
}
double getTemprature(double temp, String unit){
if((unit.equals("F"))||(unit.equals("f"))){
double c= (temp - 32) / 1.8;
JOptionPane.showMessageDialog(null,c+" Celsius");
}
else if((unit.equals("C"))||(unit.equals("c"))){
double f=((9.0 / 5.0) * temp) + 32.0;
}
}
}
Related
import java.io.*;
public class Main {
public static void main(String args[])throws Exception{
String MidtermLecGrade, MidtermLabGrade;
String FinalLecGrade, FinalLabGrade;
Float MG, temp;
Float FG;
Float Average;
Float SemG;
double a =0.6;
double b = 0.4;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your Midterm Lecture Grade:");
MidtermLecGrade=br.readLine();
System.out.print("Enter your Midterm Lab Grade:");
MidtermLabGrade=br.readLine();
temp= (a * MidtermLecGrade) + (b*MidtermLabGrade);
MG = Float.parseFloat(temp);
System.out.println("Your Midterm Grade is :" + MG);
}
}
error: bad operand types for binary operator '*'
temp= (a * MidtermLecGrade) + (b*MidtermLabGrade);
^
first type: double
second type: String
error: bad operand types for binary operator '*'
temp= (a * MidtermLecGrade) + (b*MidtermLabGrade);
^
first type: double
second type: String
error: incompatible types: Float cannot be converted to String
MG= Float.parseFloat(temp);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
You need to convert a and b variables to float.
Also you need parse the user input to float.
No need for other variables.
public static void main(String args[]) throws Exception {
String MidtermLecGrade, MidtermLabGrade;
Float temp;
float a = 0.6f;
float b = 0.4f;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your Midterm Lecture Grade:");
MidtermLecGrade = br.readLine();
System.out.print("Enter your Midterm Lab Grade:");
MidtermLabGrade = br.readLine();
temp = ((a * Float.parseFloat(MidtermLecGrade)) + (b * Float.parseFloat(MidtermLabGrade)));
System.out.println("Your Midterm Grade is :" + temp);
}
String MidtermLecGrade, MidtermLabGrade;
double a =0.6;
double b = 0.4;
//...
temp= (a * MidtermLecGrade) + (b*MidtermLabGrade);
a is a double
MidtermLecGrade is a String
double * String makes no sense, hence your error
At a guess, you will need to convert the String value to a Double. See Double.parseDouble(String)
package tempconverter;
import java.util.*;
import java.util.Scanner;
public class TempConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double tem;
System.out.print("Enter number: ");
double temp = sc.nextDouble();
System.out.println("Convert to Celsius or Fahrenheit (C or F): ");
int input = sc.nextInt();
if (input == 'C'){
System.out.println("Fahrenheit to Celcius is: " + toCelsius(temp));
}else if(input == 'F'){
toFahrenheit(temp);
}
public static double toCelsius(double cels){
double far = 5/9.0*(cels-32);
return far;
}
public static void toFahrenheit(double fahr){
double tem = 9/5.0*fahr+32;
System.out.println("Celsius to Fahrenheit: " + toFahrenheit(tem));
}
}
I refactored your code. You were having a recursive call inside one of your methods and your method were not returning values.
public static void main(String[] args) {
String name = null;
float temperature;
Scanner in = new Scanner(System.in);
System.out.println("Enter temperature: " );
temperature = in.nextFloat();
System.out.println("Convert to Celsius or Fahrenheit (C or F): ");
name = in.next();
if (name.equals("C")) {
System.out.println("Fahrenheit to Celcius: " + toCelsius(temperature));
}else if (name.equals("F")){
System.out.println("Celsius to Fahrenheit: " + toFahrenheit(temperature));
}
}
public static double toCelsius(double cels){
double far = 5/9.0*(cels-32);
return far;
}
public static double toFahrenheit(double fahr){
double tem = 9/5.0*fahr+32;
return tem;
}
The main problem is that you have a cycle in your code. The method toFahrenheit calls toFahrenheit again inside the println. This leads to an infinite loop which will result in a stackoverflow at some point. Move the println outside of the method like in the toCelsius and return the converted value.
Apart from this you have a problem as 'C' and 'F'.
I'm new to java and I'm trying to write a program that converts Celsius to Fahrenheit
import java.util.Scanner;
public class Temps
{
public static void main(String[] args)
{
System.out.print("Enter temp(70 f or 20 c): ");
double temp = keyboard.nextDouble();
String units = keyboard.next();
if (units.equal("f"))
newtemp = ftoc(temp);
else if (units.equals("c"))
newtemp = ctof(temp);
else System.err.println("units must be c or f");
}
public static double ftoc (int c)
return (( 5.0 / 9.0) * (c - 32));
}
public static double ctof (int f)
{
return ((9.0/5.0)* f+32);
}
}
can someone explain to me what I did wrong.
Quite a few problems
see comments in fixed code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter temp(70 f or 20 c): ");
double temp = keyboard.nextDouble();
String units = keyboard.next();
double newtemp = -1; // not declared
if (units.equals("f")) // should be equals
newtemp = ftoc(temp);
else if (units.equals("c"))
newtemp = ctof(temp);
else System.err.println("units must be c or f");
System.out.println("the new temp is " + newtemp); // need to print it out
}
public static double ftoc (double c) { // take a double
return (( 5.0 / 9.0) * (c - 32));
}
public static double ctof (double f) // take a double
{
return ((9.0/5.0)* f+32);
}
I'm trying to make a unit conversion program but I keep receiving value as infinity. I'm not sure where I need to fix since it's not giving me errors. I only tested oz to ml to make sure I'm doing it correctly but I'm receiving infinity as the answer.
UnitConverter.java:
public class UnitConverter {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor;
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
public double toOz(double amount) {
return (amount * factor);
}
public double fromOz(double amount) {
return (amount / factor);
}
public double toMl(double amount) {
return (amount * factor);
}
public double fromMl(double amount) {
return (amount / factor);
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
System.out.print("Value ");
double val = in.nextDouble();
double oz = from.toOz(val);
double converted = to.fromOz(oz);
System.out.println(val + " " + fromUnit + " = " + converted + " " + toUnit);
}
}
Sample input:
Convert from: oz
Convert to: ml
Value 12
Output:
12.0 oz = Infinity ml
Initialize the factor varible with one. A java with default give 0 to primitive double,
class UnitConvertor {
final double oz_TO_ml = 29.5735;
final double gal_TO_g = 3.78541;
final double lb_TO_kg = 0.453592;
final double inc_TO_mm = 25.4;//Inc is inches
final double ft_TO_cm = 30.48;
final double mi_TO_km = 1.60934;
double factor=1;//initialize with 1
But I am still not sure that what is the check you are using if the user input is 'ml'.
public UnitConverter(String unit)
{
if (unit.equals("oz"))
{
factor = oz_TO_ml;
} else if (unit.equals("gal"))
{
factor = gal_TO_g;
} else if (unit.equals("lb"))
{ factor = lb_TO_kg;
}
}
If you pass "ml" the factor will be zero
Your design currently needs two of these but you really only need one as "oz" has everything it needs to do the conversion.
Ignore the the toUnit in your line input code and just use fromUnit
Edit : I'll show you an alternative way to do things, it just supports one convert to show the rough design. Note the method calls are now static because you will only ever need one instance of them
UnitConverter.java
public class UnitConverter
{
private static final double oz_TO_ml = 29.5735;
public static double convert(String fromType, String toType,double amount) throws IllegalArgumentException
{
if (fromType.equals("oz") && toType.equals("ml"))
{
return (amount * oz_TO_ml);
}
else
{
throw new IllegalArgumentException("The combination of converting " + fromType + " to " + toType + " is not supported");
}
}
}
Calculator.java:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();
System.out.print("Value ");
double val = in.nextDouble();
System.out.println(val + " " + fromUnit + " = " + UnitConverter.convert(fromUnit,toUnit,val) + " " + toUnit);
}
}
Your UnitConverter class constructor only knows about 3 units: oz, gal, and lb. If you instantiate it with one of those, it will correctly assign the factor and be able to convert units, as seen below:
public UnitConverter(String unit) {
if (unit.equals("oz")) {
factor = oz_TO_ml;
} else if (unit.equals("gal")) {
factor = gal_TO_g;
} else if (unit.equals("lb")) {
factor = lb_TO_kg;
}
}
However, in your Calculator class, you have this line:
UnitConverter from = new UnitConverter(fromUnit);
UnitConverter to = new UnitConverter(toUnit);
If you run your program with your sample input, from is oz and to is ml. But if you instantiate UnitConverter with the unit ml, what does factor get set to? According to your constructor, it is never set, and so it retains its default value of 0.0.
Later, you call this line:
double converted = to.fromOz(oz);
This runs the fromOz method
public double fromOz(double amount) {
return (amount / factor);
}
Which divides by the factor, which is 0.0. This is the source of your Infinity output.
As the other answer says, you don't need to have two UnitConverter objects to perform this calculation. The factor is correct to convert between ounces and millilitres, so this Calculator code is sufficient.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Convert from: ");
String fromUnit = in.nextLine();
UnitConverter from = new UnitConverter(fromUnit);
System.out.print("Value ");
double val = in.nextDouble();
double result = from.toMl(val);
System.out.println(val + " " + fromUnit + " = " + result + " ml.");
}
}
If you wanted to keep your current calculator code, you would need to add a condition in your UnitConverter constructor for a scalefactor for ml (1.0). However, I think this approach is flawed because what happens, for example, when you try to convert between oz and inches? The conversion makes no sense but your architecture would not prevent it.
Ok,so I'm a complete novice at programming and I just started coding in Java. I tried to write a code for temperature conversion (Celsius to Fahrenheit) and for some reason it simply won't run! Please, help me find out errors in this code(however silly it may be).
Here's the code:
package tempConvert;
import java.util.Scanner;
public class StartCode {
Scanner in = new Scanner(System. in );
public double tempInFarenheit;
public double tempInCelcius;
{
System.out.println("enter the temp in celcius");
tempInCelcius = in .nextDouble();
tempInFarenheit = (9 / 5) * (tempInCelcius + 32);
System.out.println(tempInFarenheit);
}
}
You forgot to write the main method which is the start point for a program to run. Let me modify your code.
import java.util.Scanner;
public class StartCode
{
Scanner in = new Scanner (System.in);
public double tempInFarenheit;
public double tempInCelcius;
public static void main (String[] args)
{
System.out.println("enter the temp in celcius");
tempInCelcius = in.nextDouble() ;
tempInFarenheit = (9/5)*(tempInCelcius+32);
System.out.println(tempInFarenheit);
}
}
I think this is going to work better for you:
import java.util.Scanner;
public class StartCode
{
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
double tempInFarenheit;
double tempInCelcius;
System.out.println("enter the temp in celcius");
tempInCelcius = in.nextDouble() ;
tempInFarenheit = 1.8*tempInCelcius+32;
System.out.println(tempInFarenheit);
}
}
You equation for Farenheit was incorrect. Integer division isn't for you, either.
You need a main method. I also suggest using an IDE such as Eclipse, which can generate the skeleton code for you (including the syntax of the main method).
import java.util.*;
public class DegreeToFahrenheit {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a temperature: ");
double temperature = input.nextDouble();
System.out.println("Enter the letter of the temperature type. Ex: C or c for celsius, F or f for fahrenheit.: ");
String tempType = input.next();
String C = tempType;
String c = tempType;
String F = tempType;
String f = tempType;
double celsius = temperature;
double fahrenheit = temperature;
if(tempType.equals(C) || tempType.equals(c)) {
celsius = (5*(fahrenheit-32)/9);
System.out.print("The fahrenheit degree " + fahrenheit + " is " + celsius + " in celsius." );
}
else if(tempType.equals(F) || tempType.equals(f)) {
fahrenheit = (9*(celsius/5)+32);
System.out.print("The celsius degree " + celsius + " is " + fahrenheit + " in fahrenheit." );
}
else {
System.out.print("The temperature type is not recognized." );
}
}
}