I am new to Java and am still getting used to the minor difference so please excuse any mistakes you may find ridiculous.
I am trying to write a program that stores temperature and can be used to call that temperature in Celsius or in Fahrenheit. My only issue comes with the command line arguments, after successfully compiling my program I enter the following:
java Driver 0.0C 32.0F
And then I get this:
Exception in thread "main" java.lang.NumberFormatException: For input string:
"0.0C"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Float.parseFloat(Float.java:452)
at Driver.main(Driver.java:47)
My program is still not completely polished up so I know that the getters can be written to be much for efficient and that the driver program doesn't even call the temperature class, but this is not my concern at the moment. My Driver is supposed to take in the input and determine from the 'C' or 'F' character whether the value is in Celsius or Fahrenheit. It then parses the string and truncates the C or F and stores the values contained in the strings as floats. I am using Eclipse and the program is object oriented, this is my code:
public class Temperature {
private float temperature;
private char scale;
// default constructor
Temperature() {
this.temperature = 0;
this.scale = 'C';
}
Temperature(float temperatureIn) {
this.temperature = temperatureIn;
this.scale = 'C';
}
Temperature(char scaleIn) {
this.temperature = 0;
this.scale = scaleIn;
}
Temperature(float temperatureIn, char scaleIn) {
this.temperature = temperatureIn;
this.scale = scaleIn;
}
float degreesC(float degreesF) {
float degreesC = (5 * (degreesF - 32)) / 9;
return degreesC;
}
float degreesF(float degreesC) {
float degreesF = (9*(degreesC / 5)) + 32;
return degreesF;
}
void setTemperature(float temperatureIn) {
temperature = temperatureIn;
}
void setScale(char scaleIn) {
scale = scaleIn;
}
void setBothValues(float temperatureIn, char scaleIn) {
temperature = temperatureIn;
scale = scaleIn;
}
int compareTemps(Temperature temp1, Temperature temp2) {
// both values will be compared in Farenheit
Temperature temp1temp = temp1;
if (temp1temp.scale == 'C') {
temp1temp.temperature = degreesF(temp1temp.temperature);
temp1temp.scale = 'F';
}
Temperature temp2temp = temp2;
if (temp2temp.scale == 'C') {
temp2temp.temperature = degreesF(temp2temp.temperature);
temp2temp.scale = 'F';
}
if (temp1temp.temperature == temp2temp.temperature) {
return 0;
}
if (temp1temp.temperature > temp2temp.temperature)
return 1;
if (temp1temp.temperature < temp2temp.temperature)
return -1;
return 0;
}
}
And the main driver program:
public class Driver {
public static void main(String[] args) {
// ints to hold the temperature values
float temp1Value = 0;
float temp2Value = 0;
// strings to hold the scale types
char temp1Scale = 'C';
char temp2Scale = 'C';
// declare objects of type temperature
Temperature firstTemp = null;
Temperature secondTemp = null;
// copy scale values of temperatures
int scaleIndex = 0;
int scaleIndex2 = 0;
if (args.length > 0) {
if (args[0].indexOf('C') != -1)
{
scaleIndex = args[0].indexOf('C');
temp1Scale = args[0].charAt(scaleIndex);
}
else if (args[0].indexOf('F') != -1)
{
scaleIndex = args[0].indexOf('F');
temp1Scale = args[0].charAt(scaleIndex);
}
if (args[1].indexOf('C') != -1)
{
scaleIndex = args[1].indexOf('C');
temp2Scale = args[1].charAt(scaleIndex2);
}
else if (args[1].indexOf('F') != -1)
{
scaleIndex = args[1].indexOf('F');
temp2Scale = args[1].charAt(scaleIndex2);
}
}
// parse the values to exclude scales and copy to strings holding temperature values
if (args.length > 0) {
temp1Value = Float.parseFloat(args[0].substring(0, scaleIndex));
temp2Value = Float.parseFloat(args[1].substring(0, scaleIndex2));
}
}
}
the exception you are getting is beacuse you passed '0.0C' to the float parser at:
tempValue = Float.parseFloat(args[1].substring(0, scaleIndex));
that is beacuse you do
scaleIndex = args[1].indexOf('F');
effectively overwriting the scaleIndex instead of setting scaleIndex2
please be open minded with my following recommendations:
object oriented means you create classes which will take up responsibility
your Temperature class stores temp in celsius and in fahrenheit too..which might be easier, but storing only for example Kelvins would mean you have a strong inner concept inside the class
when someone asks for C or F it calculates from the K
after that the Temperature class's constructor should be responsible for parsing '0.0C' and '42.0F'
It is better you take inputs as <temp1> <unit1> <temp2> <unit2>. This way you'll get all the parameter you need in the desired format. You can now parse args[0] and args[2] for tempValues and the other two parameter for the units. Even better, just take <temp1> <temp2> as you command line arguments and decide that <temp1> is in degC and <temp2> is in F.
Related
So for this program, the mean and median are supposed to calculated and displayed but I do not think the data I am inputting is getting put into the array because it runs without error but does not display any data I have put into it.
public static double Mean(double[] gradeArray, int numGrades) {
double totalArray = 0.0;
double mean;
for (int i = 0; i < numGrades; i++) {
totalArray = gradeArray[i] + totalArray;
}
mean = totalArray / numGrades;
return mean;
}
public static double Median(double[] gradeArray, int numGrades) {
double median;
Arrays.sort(gradeArray, 0, numGrades);
if (numGrades % 2 == 0) {
median = ((gradeArray[(numGrades / 2)] + gradeArray[(numGrades / 2 + 1)]) / 2);
} else {
median = gradeArray[(numGrades / 2)];
}
return median;
}
private void Enter_Grades_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
double[] totalArray = new double[25];
String text_box_input_str = null;
double text_box_input_num = 0;
int numGrades = 0;
String num_grades_str;
DecimalFormat df = new DecimalFormat("#0.0##");
do {
try {
text_box_input_str = JOptionPane.showInputDialog(null, "Enter Item Price", "Enter Price", JOptionPane.PLAIN_MESSAGE);
if (text_box_input_str == null || text_box_input_str.isEmpty()) {
return;
}
if (text_box_input_num > 0) {
double[] gradeArray = null;
gradeArray[numGrades] = text_box_input_num;
numGrades++;
num_grades_str = Integer.toString(numGrades);
num_grades_text.setText(num_grades_str);
Mean_Text.setText(df.format(Mean(gradeArray, numGrades)));
Median_Text.setText(df.format(Median(gradeArray, numGrades)));
}
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught");
JOptionPane.showMessageDialog(null, "You Must Input numeric data!", "Bad Data!", JOptionPane.ERROR_MESSAGE);
}
} while (text_box_input_str != null && !text_box_input_str.isEmpty());
}
I expect the program to calculate the data that is inputted and calculate the mean and median and then display the totals
it looks like text_box_input_num is set to 0, never updated, but then there is an if check if it's > 0
Rather than pointing out the problem with your code directly, I'll give some pointers on how to find it yourself.
break your code down into smaller parts
for each part, write both the method and the tests that prove the method does what you expect
once the individual parts are working, write the method (and tests) that use them.
You'll end up with several methods with names like getValues, hasValue, printError, checkValidValue, showMedian etc. all of which do exactly what you want.
I guarantee that if you do that it'll become pretty clear very quickly what's wrong.
The assignment is to create a class called Temp that runs against the instructors TestTemp class which he provided to us for free. So far everything seems to test out pretty well except for my out put in the toString that we are supposed to use. It is supposed to format like the commented out section but doesn't seem to be working. I posed the TestTemp class and my code for the Temp class. I feel like I am missing something little but just need a nudge in the right direction and my instructor doesn't have office hours again until after the assignment is due. I also pasted the assignment instructions he added to the assignment.
The class will be called Temp
Add a compareTo method. (returns -1 if the invoking object has a lower
temp, 0 if the same, 1 if larger)
Add a static counter (object id)to keep track of how many Temperature
objects have been created(1,2,3,...)
Add a static method to tell you how many Temperature objects have been
created.
Include a toString method that displays the object as follows(assumes
3rd one created):
Object Id: 3 Temperature in F: 32.0 Temperature in C: 0.0
Note that calling getF or getC returns the value only. They do not
change the native data.
To be clear the only methods are as follows: 4 constructors, getF,
getC, setDegrees, setScale, equals, toString, compareTo and a static
getTempCount that returns the total number of objects that have been
created.
Note that the getters will return the degrees in the requested scale
rounded to a tenth of a degree. Never round the native data.
Note that the equals method will return true if the temperatures are
the same when compared in celsius (that was rounded to a tenth of a
degree).
Be sure to make great use of this() and have only one contructor do
any real work.
Besure to validate the scale and follow the default (C) if a "bad
scale" is sent in
No need to validate the degrees and worry about things such as
absolute zero and so on.
NOTE: Your Temp class must work correctly with the TestTemp class
supplied in UNIT-04-CodeSamples
//32 - 212 180 ticks
//
//0-100 1/10
//
public class TestTemp
{
public static void main(String [] args)
{
// only one constructor does any real work
Temp temp1 = new Temp(); // 0 C
Temp temp2 = new Temp(32); // 32 C
Temp temp3 = new Temp('F'); // 0 F
Temp temp4 = new Temp(32, 'F'); // 32 F
Temp temp5 = new Temp(); // 0 C
temp5.setDegrees(10);
temp5.setScale('F'); // 10 F
System.out.println("C: " + temp1.getC() ); // C: 0.0
System.out.println("F: " + temp1.getF() ); // F: 32.0
System.out.println(temp1.equals(temp4)); // true
System.out.println(temp1.equals(temp2)); // false
System.out.println("You have " + Temp.getTempCount() ); // You have 5
if( temp3.compareTo(temp5)< 0 ) //temp3 is lower than than temp5
{
System.out.println("temp3 is lower than than temp5");
}
else
{
System.out.println("temp3 is same or larger than temp5");
}
System.out.println(temp1);
/*
TEMP OBJECT #1
IN C: 0.0
IN F: 32.0
*/
}
}
public class Temp implements Comparable<Temp>
{
private double degrees;
private char scale;
private static int tempCount = 0;
private int id;
public Temp()
{
this.degrees = 0;
this.scale = 'C';
// this(0.0, 'C');
}
public Temp(double degrees)
{
this.degrees = degrees;
this.scale = 'C';
// this(degrees, 'C');
}
public Temp(char scale)
{
this.degrees = 0;
this.scale = scale;
// this(0.0, scale);
}
public Temp(double degrees, char scale)
{
this.id = ++tempCount;
this.degrees = degrees;
this.scale = scale;
//(degrees, scale);
}
public static int getTempCount()
{
return tempCount;
}
public int getId()
{
return this.id;
}
public void setScale(char scale)
{
if(scale == 'C')
{
this.scale = scale;
}
else
{
this.scale = 'F';
}
}
public void setDegrees(double degrees)
{
this.degrees = degrees;
}
public double getC()
{
if(scale == 'C')
{
return degrees;
}
else
{
return (double)(5.0 * (degrees-32)/9.0);
}
}
public double getF()
{
if(scale == 'F')
{
return (double) degrees;
}
else
{
return (double)(9.0*(degrees)/5.0)+32;
}
}
#Override
public int compareTo(Temp obj)
{
if(this.getC() < obj.getC() )
{
return -1;
}
if(this.getC() > obj.getC() )
{
return 1;
}
return 0;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Temp))
{
return false;
}
Temp other = (Temp)obj;
return this.getC() == other.getC();
}
**public String toString()
{
return String.format("TEMP OBJECT ", this.id) + "\n" +
String.format("IN C: ", this.getC() ) + "\n" +
String.format("IN F: ", this.getF() );
}**
}
You need place holders in the formatter, Your toString method should be like
public String toString()
{
return String.format("TEMP OBJECT %d", this.id) + "\n" +
String.format("IN C: %.2f", this.getC() ) + "\n" +
String.format("IN F: %.2f", this.getF() );
}
Here %d for integers and %f for decimals. and the .2f limits the number of decimal places to 2. See some more examples here
Your use of String.format shouldn't require multiple creations. Just use one.
return String.format("TEMP OBJECT: $d, %nIN C: %.2f, %nIN F: %.2f", this.id, this.getC(), this.getF());
Modify the precision of the floating points by altering the value after the decimal point %.2f to %.5f will print 0.00000 instead of 0.00 for example.
If you have anymore questions on the use of format, I recommend reading the documentation for it as well to see what else it can do. Link
Edit: Added newline breaks. Forgot to mention just put %n for a newline. Do not space, after them, unless you want your newline to start with a space.
I don't want to solve an equation and my question is not about Graphs and Trees Data Structures. I am trying to generate Data Points for graph from an equation given by user. I want efficient algorithm, easy to use and easy to maintain data structures. I have two solutions in mind
1: This is trivial and I have seen in many Applications.
String expr = "2*x+3*x";
Evaluator evaluator = new Evaluator();//I have this class
for (int i = start; i < end; i += step)
{
evaluator.setConstant("x", i);
double ans = evaluator.evaluate(expr);
}
This is very slow because each time every step is repeated like tokenzing, verifying, conversion to RPN, preparing stacks and queues and at last result calculation. The possible solution to this problem is somehow caching all stacks and queues but after that a comparison would be required between current expression and previous expression to use last stored state.
2: Currently I am developing second solution. The purpose of this is efficiency and would be used in Symbolic calculation in future.
So far my implementation
Variable.java
import java.text.DecimalFormat;
public class Variable
{
private final double pow;
private final double coefficient;
private final String symbol;
public Variable(String symbol)
{
this.symbol = symbol;
this.pow = 1.0;
this.coefficient = 1.0;
}
public Variable(String symbol, double coefficient, double pow)throws IllegalArgumentException
{
if (coefficient == 0.0)throw new IllegalArgumentException("trying to create variable with coefficient 0");
if (pow == 0.0)throw new IllegalArgumentException("trying to create variable with exponent 0");
this.symbol = symbol;
this.pow = pow;
this.coefficient = coefficient;
}
public final String getSymbol()
{
return this.symbol;
}
public final double getPow()
{
return this.pow;
}
public final double getCoefficient()
{
return this.coefficient;
}
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
DecimalFormat decimalFormat = new DecimalFormat("#.############");
if (coefficient != 1.0)builder.append(decimalFormat.format(this.coefficient));
builder.append(this.symbol);
if (this.pow != 1.0)builder.append("^").append(decimalFormat.format(this.pow));
return builder.toString();
}
/*
* Stub Method
* Generate some unique hash code
* such that chances of key collision
* become less and easy to identify
* variables with same power and same
* symbol*/
#Override
public int hashCode()
{
return 0;
}
}
Equation.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class Equation
{
private final ArrayList<Boolean> operations;
private final HashMap<String, Variable> variableHashMap;
private int typesOfVariables;
public Equation(Variable variable)
{
this.variableHashMap = new HashMap<>();
this.operations = new ArrayList<>();
this.typesOfVariables = 1;
this.variableHashMap.put(variable.getSymbol(), variable);
}
/*Stub Method*/
public void addVariable(Variable variable, boolean multiply)
{
/*
* Currently not covering many cases
* 1: Add two variables which have same name
* and same pow.
* 2: variable which are wrapped inside functions e.g sin(x)
* and many other.*/
if (multiply && variableHashMap.containsKey(variable.getSymbol()))
{
Variable var = variableHashMap.get(variable.getSymbol());
Variable newVar = new Variable(var.getSymbol(), var.getCoefficient() * variable.getCoefficient(), var.getPow() + variable.getPow());
/*
* Collision chances for variables with same name but
* with different powers*/
this.variableHashMap.replace(var.getSymbol(), newVar);
}
else
{
++this.typesOfVariables;
this.variableHashMap.put(variable.getSymbol(), variable);
}
this.operations.add(multiply);
}
/*Stub Method
*Value for every variable at any point will be different*/
public double solveFor(double x)
{
if (typesOfVariables > 1)throw new IllegalArgumentException("provide values for all variables");
Iterator<HashMap.Entry<String, Variable>> entryIterator = this.variableHashMap.entrySet().iterator();
Variable var;
double ans = 0.0;
if (entryIterator.hasNext())
{
var = entryIterator.next().getValue();
ans = var.getCoefficient() * Math.pow(x, var.getPow());
}
for (int i = 0; entryIterator.hasNext(); i++)
{
var = entryIterator.next().getValue();
if (this.operations.get(i))ans *= var.getCoefficient() * Math.pow(x, var.getPow());
else ans += var.getCoefficient() * Math.pow(x, var.getPow());
}
return ans;
}
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
Iterator<HashMap.Entry<String, Variable>> entryIterator = this.variableHashMap.entrySet().iterator();
if (entryIterator.hasNext())builder.append(entryIterator.next().getValue().toString());
Variable var;
for (int i = 0; entryIterator.hasNext(); i++)
{
var = entryIterator.next().getValue();
if (this.operations.get(i))builder.append("*").append(var.toString());
else builder.append(var.toString());
}
return builder.toString();
}
}
Main.java
class Main
{
public static void main(String[] args)
{
try
{
long t1 = System.nanoTime();
Variable variable = new Variable("x");
Variable variable1 = new Variable("x", -2.0, 1.0);
Variable variable2 = new Variable("x", 3.0, 4.0);
Equation equation = new Equation(variable);
equation.addVariable(variable1, true);//2x+x
equation.addVariable(variable2, true);
for (int i = 0; i < 1000000; i++)equation.solveFor(i);//Calculate Million Data Points
long t2 = System.nanoTime();
System.out.println((t2-t1)/1000/1000);
System.out.println(equation.toString());
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
Am I going in right direction?
Is there any commonly used Algorithm for this problem?
My main goal is efficiency, code cleanness and code maintainability.
Note: I am not native English speaker so please ignore any grammatical mistake.
Thanks.
I do not see any problem with your first code. Yes may be at every step your code "repeat like tokenzing, verifying, conversion to RPN, preparing stacks and queues and at last result calculation", but in the end all of this is just linear number of steps. So I fail to see how it can make it really slow.
One of the biggest screens I have seen was 2560x1440 pixels, which means that most of the time you would need less than 2500 points to draw your graph there.
If you point is code cleanness and code maintainability, then most probably a code consisting of 5 lines is better than the code consisting of 200.
I am currently writing a program that will read through a designated text file that checks the transaction values of each buy/sell/summary and checks the arithmetic such that if the transactions from the buy and sell statements do not equal the total transaction amount that was given in the summary then it outputs an error and closes the program. But currently my method scanMoneyValue has an error that says it's not returning a double, when in fact it is. Is there a different way I should go about returning the values from my method? Here is my code for reference:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class RecurrsionFileChecker {
public static void main(String[] args) {
int result;
//File Chooser Window
JFileChooser chooser = new JFileChooser("/home/nick/workspace/CS 1410-001/src/assignment03");
chooser.setDialogTitle("Please choose a file to be checked");
result = chooser.showOpenDialog(null);
//User Cancelled the chooser
if (result == JFileChooser.CANCEL_OPTION)
return;
File inputfile = chooser.getSelectedFile();
try
{
Scanner in = new Scanner(inputfile);
//Call Method to look at next transaction
scanNextTransaction(in);
}
catch (IOException e)
{
System.out.println("Could not read file: " + inputfile);
}
}
/**
* Returns double if the parameter Scanner has an error that does,
* not match the summary before it.
*
* #param s Any scanner
* #return double if Summaries don't match.
*/
public static double scanNextTransaction(Scanner s)
{
String buy, sell, summary, date;
double amount = 0, referenceValue, total = 0;
summary = s.next();
date = s.next();
referenceValue = scanMoneyValue(s);
while (s.hasNext())
{
if (s.next() == "Buy")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Sell")
{
date = s.next();
amount = scanMoneyValue(s);
}
if(s.next() == "Summary")
{
amount = scanSubSummary(s);
}
//add the transactions
total = total + amount;
}
return total;
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
public static double scanSubSummary(Scanner sub)
{
String summaryDate, transDate, transType;
int summarySubEntries, count = 0;
double transValue, summaryValue = 0, totalValue = 0, summaryAmount;
summaryDate = sub.next();
summaryAmount = scanMoneyValue(sub);
summarySubEntries = sub.nextInt();
while (count != summarySubEntries)
{
transType = sub.next();
if (transType == "Summary")
{
summaryValue = scanSubSummary(sub);
}
transValue = scanMoneyValue(sub);
totalValue = transValue + totalValue + summaryValue;
count++;
}
if (totalValue != summaryAmount)
{
System.out.print("Summary error on " + summaryDate + ".");
System.out.println("Amount is $" + summaryAmount + ", " + "should be $" + totalValue + ".");
}
return totalValue;
}
}
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
If the if condition fails then there's no return statement. You have a return inside of the condition but not outside. You'll need to add a return statement at the end, or throw an exception if not having a dollar sign is an error.
Okay, looking at the only relevant part of your code:
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
}
You do return a value if dollar starts with a $... but what do you expect to happen if it doesn't start with $? Currently you reach the end of the method without returning anything, which isn't valid.
You should probably throw an exception, if this is unexpected data that you can't actually handle.
Additionally, you shouldn't really use double for currency values anyway, due to the nature of binary floating point types. Consider using BigDecimal instead.
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
if(dollar.charAt(0) == '$')
{ //convert string to a double
String amount = dollar.substring(1);
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
//NEED RETURN STATEMENT HERE
}
The error you get is because when you write a function all branches of that function must return a value of the correct type. In your case, if the if-statement fails it hits the end of the function without returning anything.
Its better to change it on
public static double scanMoneyValue(Scanner in)
{
String dollar = in.next();
String amount = dollar.replaceAll("[^\\d.]+", "")
double complete = Double.parseDouble(amount);
complete = complete * 100;
return complete;
}
link on explain - Parsing a currency String in java
I can convert from fahrenheit to celcius, but not the other way around. I have attached the code below. Hopefully it's enough to see what is going on.
public void actionPerformed(ActionEvent arg0) {
double temps = 0, temp1 = 0;
String instrings;
instrings = temp.getText();
if(instrings.equals(""))
{
instrings = "0";
temp.setText("0");
}
temps = Double.parseDouble(instrings);
instrings = temp.getText();
if(instrings.equals(""))
{
instrings = "0";
temp.setText("0");
}
temp1 = Double.parseDouble(instrings);
if(arg0.getActionCommand().equals("C")){
temps = (( temps * 9)/5+32);
DecimalFormat formatters = new DecimalFormat("#,###,###.###");
results.setText(""+formatters.format(temps));
}
else if(arg0.getActionCommand().equals("F"));
{
temp1 = (((temps - 32)/9)*5);
DecimalFormat formatters = new DecimalFormat("#,###,###.###");
results.setText(""+formatters.format(temp1));
}
}
Put a
System.out.println(arg0.getActionCommand());
in your method, and supposedly you will see that it is not "C" when using the Celsius button.
Generally, look at the console to see if there are any error messages around.
Another idea: You are using two double variables temps and temp1, parsing the instrings into both of them, and setting then one of them to the result. Why so complicated?
In general, I would recommend to not use the getActionCommand() method, but to give each button an own ActionListener. You can use an anonymous class for this. As both cases do almost the same, use two subclasses of a inner (or even local) class here:
abstract class ConversionListener implement ActionListener {
DecimalFormat formatter = new DecimalFormat("#,###,###.##");
public void actionPerformed(ActionEvent e) {
String input = temp.getText();
if (input.equals("")) {
input = "0";
temp.setText(input);
}
double number = Double.parseDouble(input);
results.setText(formatter.format(convert(number)));
}
/** to implement by subclasses */
abstract double convert(double number);
}
celsiusToFahrenheit.addActionListener(new ConversionListener() {
double convert(double celsius) {
return number * 9 / 5 + 32;
}
});
fahrenheitToCelsius.addActionListener(new ConversionListener() {
double convert(double fahrenheit) {
return (fahrenheit - 32) / 9 * 5;
}
});
Not sure what you are having trouble with but here is how to convert Celsius to Fahrenheit in Java.
float celsius = celsius value
float c=Float.parseFloat(celsius);
float f = 32 + 9*c/5;
Change from
temp1 = (((temps - 32)/9)*5);
to
temp1 = (((temps - 32)*5)/9);
instead.
On this part:
instrings = temp.getText();
if(instrings.equals(""))
{
instrings = "0";
temp.setText("0");
}
temps = Double.parseDouble(instrings);
instrings = temp.getText();
if(instrings.equals(""))
{
instrings = "0";
temp.setText("0");
}
temp1 = Double.parseDouble(instrings);
Am I missing something or is temps and temp1 both getting set to the same value? Or is it possible that between the temps assignment the temp.getText() could return a different value?
If it's the same, start by rewriting it to
instrings = temp.getText();
if(instrings.equals(""))
{
instrings = "0";
temp.setText("0");
}
temps = Double.parseDouble(instrings);
temp1 = Double.parseDouble(instrings);
or even temp1 = temps
Also, some better naming of variables might be easier, temps, temp and temp1 are all very similar. One appears to be text from a control and the other 2 are numeric values.
Even names like 'inputTemperature' and 'calculatedTemperature' go a long way to making the code more readable.
This doesn't help solve your problem, but might help debugging in the future.