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);
}
Related
When I run the program and and put in a couple mortgages and then end the program it prints out the entire array of objects, mortgageArray[], but for some reason it is only printing out the last mortgage you entered. Not sure why can anybody help me out? I think the problem may lie when instantiating the objects into the array.
Mortgage Class
import java.util.*;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Mortgage {
private static int loanAmount;
private static int term;
private static double interestRate;
private static String accountNum;
private static String lastName;
private static double monthlyPayment;
private static double totalPayment;
public Mortgage(int loanAmount1, int term1, double interestRate1, String accountNum1){
loanAmount = loanAmount1;
term = term1;
interestRate = interestRate1;
accountNum = accountNum1;
}
public void promotional(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
lastName = getLastName();
accountNum = getAccountNum();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public void unique(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
m.storeLoanAmount();
m.storeInterestRate();
m.storeTerm();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public Mortgage(){
//dummy constructor
}
public static int getLoanAmount(){
return loanAmount;
}
public void storeLoanAmount(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount of the loan (Ex:75000): ");
int loanAmount1 = s.nextInt();
while(loanAmount1 < 75000 || loanAmount1 > 1000000){
System.out.println("\tValid Loan Amounts are $75000-$1000000");
System.out.println("\tPlease re-enter loan amount without $ or commas (Ex:75000): ");
loanAmount1 = s.nextInt();
}
loanAmount = loanAmount1;
}
public static int getTerm(){
return term;
}
public void storeTerm(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number of years for the loan: ");
int term1 = s.nextInt();
while(term1 < 10 || term1 > 40){
System.out.println("\tValid Loan Terms are 10-40");
System.out.println("\tPlease re-enter valid number of years: ");
term1 = s.nextInt();
}
term = term1;
}
public static double getInterestRate(){
return interestRate;
}
public void storeInterestRate(){
Scanner s = new Scanner(System.in);
System.out.println("Enter yearly interest rate (Ex: 8.25): ");
double interestRate1 = s.nextDouble();
while(interestRate1 < 2 || interestRate1 > 7){
System.out.println("\tValid Interest Rates are 2% - 7%");
System.out.println("\tPlease re-enter valid yearly interest rate (Ex: 8.25): ");
interestRate1 = s.nextDouble();
}
interestRate = interestRate1;
}
public String getLastName(){
return lastName;
}
public void storeLastName(){
Scanner s = new Scanner(System.in);
System.out.println("Enter customer's Last Name Only: ");
String lastName1 = s.nextLine();
lastName = lastName1;
}
private double calcMonthlyPayment(){
int months = term * 12;
double monthlyInterest = (interestRate / 12 / 100);
double monthlyPay = (loanAmount * monthlyInterest) / (1 - Math.pow(1+ monthlyInterest, -1 * months));
return monthlyPay;
}
private double calcTotalPayment(){
double totalPay = calcMonthlyPayment() * term * 12;
return totalPay;
}
public String getAccountNum(){
return accountNum;
}
public void storeAccountNum(){
StringBuilder accountNum1 = new StringBuilder();
Random rand = new Random();
int accNum = rand.nextInt(9900);
accNum += 100;
accountNum1.append(lastName.substring(0,4));
accountNum1.append(accNum);
accountNum = accountNum1.toString();
}
public String toString(){
DecimalFormat df = new DecimalFormat("#,###.00");
String strMonthlyPayment = ("$" + df.format(calcMonthlyPayment()));
String strTotalPayment = ("$" + df.format(calcTotalPayment()));
return("Account Number: " + accountNum + "\nThe monthly payment is " + strMonthlyPayment + "\nThe total payment is " + strTotalPayment);
}
}
MortgageApp Class
import java.util.*;
public class MortgageApp {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Mortgage m = new Mortgage();
int size = 10;
Mortgage [] mortgageArray = new Mortgage [size];
int index = 0;
for(index = 0; index < size; index++){
int choice;
System.out.println("\nPlease choose from the following choices below:");
System.out.println("\t1) Promotional Load (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("\n\t Please enter your selection (1-3): ");
choice = s.nextInt();
while(choice < 1 || choice > 3){
System.out.println("\t\tInvalid Choice. Please select 1, 2, or 3: ");
choice = s.nextInt();
}
if(choice == 1){
m.promotional();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(250000, 20, 3.2, accountNum1);
System.out.println("PROMOTIONAL LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 2){
m.unique();
int loanAmount = m.getLoanAmount();
int term = m.getTerm();
double interestRate = m.getInterestRate();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(loanAmount, term, interestRate, accountNum1);
System.out.println("UNIQUE LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 3){
System.out.println("\nPROGRAM COMPLETE");
System.out.println("Contents of Array...");
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[j].toString() + "\n");
}
}
index = 10;
}
}
}
}
The problem is with your loop at the end
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[1].toString() + "\n");
}
}
It always prints the element at index 1.
Should be
System.out.println(mortgageArray[j].toString() + "\n");
All your fields in the class Mortgage are static.
To fix this, simply remove the static keyword:
private int loanAmount;
private int term;
private double interestRate;
private String accountNum;
private String lastName;
private double monthlyPayment;
private double totalPayment;
Static fields don't belong to an instance, but to the class that gets instantiated. So everytime you call one of your getter-methods, the previous value (of all your instances) will be overriden.
If you are not familiar with classes and objects in Java, this tutorial might be helpfull for you: Understanding Class Members
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 getting the prompt to enter an integer but nothing after that. Can someone tell me why my results are not printing?
import java.util.Scanner;
public class ChapterThreeQuiz {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit integer: ");
double answer = input.nextDouble();
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
if (x == z && y == y && z == x)
System.out.println(answer + " is a palindrome! ");
else
System.out.println(answer + " is not a palindrome");
}
}
double answer = input.nextDouble();
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
Your code is waiting for 4 different inputs. If you input all 4, it will run - but something is clearly wrong with your logic.
As others mentioned, you are a) working with doubles and b) trying to read too many numbers:
import java.util.Scanner;
public class ChapterThreeQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit integer: ");
// Read an int
int answer = 0;
try {
answer = input.nextInt();
}
catch (InputMismatchException ex) {
// Handle error
}
// Make sure it's 3 digits
if (answer < 100 || answer >= 1000) {
// Do something with bad input
}
else {
// Just need to check if first and third digits are equal.
// Get those values using integer math
int digit1 = answer / 100;
int digit3 = answer % 10;
if (digit1 == digit3) {
System.out.println(answer + " is a palindrome! ");
}
else {
System.out.println(answer + " is not a palindrome");
}
}
}
}
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
/*
OUTPUT:
Enter a string : MADAM
Entered string is a palindrome.
Enter a string : 15351
Entered string is a palindrome.
*/
You are using wrong logic here.If you want to check for palindrome, you should not use double.Hope this code helps!
after long hard work, I have finally completed (almost) my java menu program. However, I am having trouble getting my return change function to work at the end of my code. It is giving very odd numbers. Any ideas?
Code:
import java.io.*;
import java.text.*;
import java.util.*;
public class JavaBurger
{
public static double amountowed = 0;
public static double amount;
public static double amount1 = 0;
public static double amount2 = 0;
public static double amount3 = 0;
public static double amount4 = 0;
public static double amount5 = 0;
public static double amount6 = 0;
public static double amount7 = 0;
public static double amount8 = 0;
public static double amount9 = 0;
public static double amount10 = 0;
static ArrayList MenuItems = new ArrayList();
public static void main(String[] args)
{
InputStreamReader inp = null;
BufferedReader input = null;
int nOption = 0;
DecimalFormat x = new DecimalFormat("###.##");
try
{
inp = new InputStreamReader(System.in);
input = new BufferedReader(inp);
while(true)
{
System.out.println("Choose a Menu Option");
System.out.println("1. Burger - 13.49");
System.out.println("2. Pasta - 16.79");
System.out.println("3. Salad - 13.49");
System.out.println("4. Salmon - 18.99");
System.out.println("5. Chicken - 16.99");
System.out.println("6. Nachos - 13.99");
System.out.println("7. Soup - 6.99");
System.out.println("8. Fajitas - 18.49");
System.out.println("9. Ribs - 23.99");
System.out.println("10. Calamari-9.99");
System.out.println("11. Clear Order");
System.out.println("12. Finish Order");
System.out.println("\nChoose an option(1-12) >> ");
System.out.println("Subtotal: $" + x.format(amount));
System.out.println("Total: $" + x.format(amount * 1.13));
System.out.println("For error correction, choose an option and enter a negative value to void the item.");
nOption = Integer.parseInt(input.readLine());
switch(nOption)
{
case 1:
Burger(input);
break;
case 2:
Pasta(input);
break;
case 3:
Salad(input);
break;
case 4:
Salmon(input);
break;
case 5:
Chicken(input);
break;
case 6:
Nachos(input);
break;
case 7:
Soup(input);
break;
case 8:
Fajitas(input);
break;
case 9:
Ribs(input);
break;
case 10:
Calamari(input);
break;
case 11:
Clear(input);
break;
case 12:
Finish(input);
break;
}
}
}
catch(Exception exp)
{
}
}
private static void Burger(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many Burgers would you like? ");
int a = Integer.parseInt(input.readLine());
double aaa = Math.pow(1 + a, a);
amount1 = (a * 13.49);
amount += amount1;
break;
}
}
private static void Pasta(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Pasta would you like? ");
int b = Integer.parseInt(input.readLine());
double bbb = Math.pow(1 + b, b);
amount2 = (bbb * 16.79);
amount += amount2;
break;
}
} private static void Salad(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many Salads would you like? ");
int c = Integer.parseInt(input.readLine());
double ccc = Math.pow(1 + c, c);
amount3 = (ccc * 13.49);
amount += amount3;
break;
}
} private static void Salmon(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Salmon would you like? ");
int d = Integer.parseInt(input.readLine());
double ddd = Math.pow(1 + d, d);
amount4 = (ddd * 18.99);
amount += amount4;
break;
}
} private static void Chicken(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Chicken would you like? ");
int e = Integer.parseInt(input.readLine());
double eee = Math.pow(1 + e, e);
amount5 = (eee * 16.99);
amount += amount5;
break;
}
} private static void Nachos(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Nachos would you like? ");
int f = Integer.parseInt(input.readLine());
double fff = Math.pow(1 + f, f);
amount6 = (fff * 13.99);
amount += amount6;
break;
}
} private static void Soup(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Soup would you like? ");
int g = Integer.parseInt(input.readLine());
double ggg = Math.pow(1 + g, g);
amount7 = (ggg * 6.99);
amount += amount7;
break;
}
} private static void Fajitas(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of 2 Fajitas would you like? ");
int h = Integer.parseInt(input.readLine());
double hhh = Math.pow(1 + h, h);
amount8 = (hhh * 18.49);
amount += amount8;
break;
}
} private static void Ribs(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many racks of Ribs would you like? ");
int i = Integer.parseInt(input.readLine());
double iii = Math.pow(1 + i, i);
amount9 = (iii * 23.99);
amount += amount9;
break;
}
} private static void Calamari(BufferedReader input) throws IOException
{
while(true)
{
System.out.println("How many orders of Calamari would you like? ");
int j = Integer.parseInt(input.readLine());
double jjj = Math.pow(1 + j, j);
amount10 = (jjj * 9.99);
amount += amount10;
break;
}
} private static void Clear(BufferedReader input) throws IOException
{
while(true)
{
amount = 0;
break;
}
} private static void Finish(BufferedReader input) throws IOException
{
while(true)
{
DecimalFormat x = new DecimalFormat("###.##");
System.out.println("Amount Due");
System.out.println("**********");
System.out.println("Subtotal:" + x.format(amount));
System.out.println("Total:" + x.format(amount * 1.13));
System.out.println("Please enter the amount tendered");
int k = Integer.parseInt(input.readLine());
double kk = Math.pow(1 + k, k);
amountowed = ((amount * 1.13) - kk);
if(amountowed == 0)
{
System.out.println("Thanks for paying with exact change!");
System.exit(0);
}
else if(amountowed < 0)
{
System.out.println("Change due:" + x.format(amountowed * -1.00));
System.exit(0);
}
else
{
System.out.println("Amount still owed:" + x.format(amountowed * -1.00));
}
}
}
}
Result:
Choose a Menu Option
1. Burger - 13.49
2. Pasta - 16.79
3. Salad - 13.49
4. Salmon - 18.99
5. Chicken - 16.99
6. Nachos - 13.99
7. Soup - 6.99
8. Fajitas - 18.49
9. Ribs - 23.99
10. Calamari-9.99
11. Clear Order
12. Finish Order
Choose an option(1-12) >>
Subtotal: $0
Total: $0
For error correction, choose an option and enter a negative value to void the it
em.
1
How many Burgers would you like?
1
Choose a Menu Option
1. Burger - 13.49
2. Pasta - 16.79
3. Salad - 13.49
4. Salmon - 18.99
5. Chicken - 16.99
6. Nachos - 13.99
7. Soup - 6.99
8. Fajitas - 18.49
9. Ribs - 23.99
10. Calamari-9.99
11. Clear Order
12. Finish Order
Choose an option(1-12) >>
Subtotal: $13.49
Total: $15.24
For error correction, choose an option and enter a negative value to void the it
em.
12
Amount Due
**********
Subtotal:13.49
Total:15.24
Please enter the amount tendered
100
Change due:270481382942152600000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000
Why am I getting wacky numbers for the change due?
Well... Is the following line needed here?
double kk = Math.pow(1 + k, k);
It completely messed up change computation, since you powered what the user inputs (k) + 1 to the kth power.
If you want to change it to a double, (double)k will do. Of course, for monetary computation, you'd better be using:
BigDecimal
cent based Integer / Long computation
I'm struggling to see why you're over-complicating your change computation so much.. Can't you simply compute amount tendered - total?
int e = Integer.parseInt(input.readLine());
double eee = Math.pow(1 + e, e);
Let's say I want 5 things.
double eee = Math.pow(1 + 5, 5)
This is 6 * 6 * 6 * 6 * 6 (i.e. a very big number). I think you just want a simple multiplication?
If you want a double from a string, use Double.parseDouble instead of Integer.parseInt. Do not do the extra pow calculation, that is making your results completely wrong.
More generally, throwing in random lines of code is rarely a good approach to compiler error reports. It is much better to understand what is going on, and deliberately fix that problem.
At some point, you will probably actually encounter floating point rounding error, and will again be advised to use BigDecimal instead of double.
First thing first ...
you dont need unneccessary while loops (Fixed in below code )
Math.pow(1 + a, a) not required.(Fixed in below code )
amount1 , amount 2 etc can be declared as Local variable (NOT Fixed in below code ) as it dont harm
private static void Burger(BufferedReader input) throws IOException
{
System.out.println("How many Burgers would you like? ");
int a = Integer.parseInt(input.readLine());
// double aaa = Math.pow(1 + a, a);// Why THis???
amount1 = ((double)a * 13.49);
amount += amount1;
}
private static void Pasta(BufferedReader input) throws IOException
{
System.out.println("How many orders of Pasta would you like? ");
int b = Integer.parseInt(input.readLine());
// double bbb = Math.pow(1 + b, b); You dont need this
amount2 = ((double)b * 16.79);
amount += amount2;
}
private static void Salad(BufferedReader input) throws IOException
{
System.out.println("How many Salads would you like? ");
int c = Integer.parseInt(input.readLine());
//double ccc = Math.pow(1 + c, c); No Need of this again
amount3 = ((double)c * 13.49);
amount += amount3;
}
} private static void Salmon(BufferedReader input) throws IOException
{
System.out.println("How many orders of Salmon would you like? ");
int d = Integer.parseInt(input.readLine());
//double ddd = Math.pow(1 + d, d); No Need
amount4 = ((double)d * 18.99);
amount += amount4;
}
private static void Chicken(BufferedReader input) throws IOException
{
System.out.println("How many orders of Chicken would you like? ");
int e = Integer.parseInt(input.readLine());
amount5 = ((double)e * 16.99);
amount += amount5;
}
private static void Nachos(BufferedReader input) throws IOException
{
System.out.println("How many orders of Nachos would you like? ");
int f = Integer.parseInt(input.readLine());
amount6 = ((double)f * 13.99);
amount += amount6;
}
private static void Soup(BufferedReader input) throws IOException
{
System.out.println("How many orders of Soup would you like? ");
int g = Integer.parseInt(input.readLine());
amount7 = ((double)g * 6.99);
amount += amount7;
}
private static void Fajitas(BufferedReader input) throws IOException
{
System.out.println("How many orders of 2 Fajitas would you like? ");
int h = Integer.parseInt(input.readLine());
amount8 = ((double)h * 18.49);
amount += amount8;
}
private static void Ribs(BufferedReader input) throws IOException
{
System.out.println("How many racks of Ribs would you like? ");
int i = Integer.parseInt(input.readLine());
amount9 = ((double)i * 23.99);
amount += amount9;
}
private static void Calamari(BufferedReader input) throws IOException
{
System.out.println("How many orders of Calamari would you like? ");
int j = Integer.parseInt(input.readLine());
amount10 = ((double)j * 9.99);
amount += amount10;
}
private static void Clear(BufferedReader input) throws IOException
{
amount = 0;
}
private static void Finish(BufferedReader input) throws IOException
{
amountowed =amount * 1.13
DecimalFormat x = new DecimalFormat("###.##");
while(amountowed >0)
{
System.out.println("Amount Due");
System.out.println("**********");
System.out.println("Subtotal:" + x.format(amount));
System.out.println("Total:" + x.format(amountowed));
System.out.println("Please enter the amount tendered");
double k = Double.parseDouble(input.readLine());
// double kk = Math.pow(1 + k, k); No Need
amountowed = (amountowed - k);
if(amountowed == 0)
{
System.out.println("Thanks for paying with exact change!");
System.exit(0);
}
else if(amountowed < 0)
{
System.out.println("Change due:" + x.format(amountowed * -1.00));
System.exit(0);
}
else
{
System.out.println("Amount still owed:" + x.format(amountowed));
}
}
}
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;
}
}
}