I'm learning Java and I wanted to create a very basic Calculator to calculate the air pressure at a certain height above sea level. However every time I try to build the code, I get an error about the local variable ... may not have been initialized.
import javax.swing.JOptionPane;
import java.lang.Math;
class barometer {
public static void main(String args[]){
String fn = JOptionPane.showInputDialog("Enter Height Above Sea Level in Metres:");
double h = Integer.parseInt(fn);
double R = 8.31432;
double g0 = 9.80665;
double M = 0.0289644;
double Pb, Tb, Lb, Hb;
String ans = "";
if (h<0){
ans = "error";
} else if (h>=0 && h<11000){
Pb = 101325.0;
Tb = 288.15;
Lb = -0.0065;
Hb = 0.0;
} else if (h>=11000 && h<20000){
Pb = 22632.1;
Tb = 216.65;
Lb = 0.0;
Hb = 11000.0;
} else if (h>=20000 && h<32000){
Pb = 5474.89;
Tb = 216.65;
Lb = 0.001;
Hb = 20000.0;
} else if (h>=32000 && h<47000){
Pb = 868.019;
Tb = 228.65;
Lb = 0.0028;
Hb = 32000.0;
} else if (h>=47000 && h<51000){
Pb = 110.906;
Tb = 270.65;
Lb = 0.0;
Hb = 47000.0;
} else if (h>=51000 && h<71000){
Pb = 66.9389;
Tb = 270.65;
Lb = -0.0028;
Hb = 51000.0;
} else if (h>=71000){
Pb = 3.95642;
Tb = 214.65;
Lb = -0.002;
Hb = 71000.0;
}
double exp = ((-g0 * M * (h-Hb))/R * Tb);
double press = Pb*Math.exp(exp);
JOptionPane.showMessageDialog(null, "The answer is " +press+ans+"Pascals", "Barometric Formula", JOptionPane.PLAIN_MESSAGE);
}
}
So what is wrong with this code?
The error message is telling you exactly what's wrong: You don't initialize all the local variables before use. So do it. When you declare your variables give them a default value.
class Foo {
public static void main(String[] args) {
int foo = 0; // initialized local variable
}
}
Set Pb, Tb, Lb, and Hb to 0 when they're declared so you have a default.
You know your code will never get an input for h that will let them not get set, but the compiler doesn't. It's worried they might never get set!
Because Pb, Tb, Lb, Hb are only initialised inside if blocks, it's possible that all the 'if' conditions will never arise, and so they'll come out the if blocks without being assigned a value. A final 'else' could help there, or giving them values before the block of conditionals.
More detailed: This branch of your multiple-case-branching is the culprit:
if (h<0){
ans = "error";
}
If this occurs, the variables Pb, Tb, Lb, Hb are not initialized, yet you still are using them in the showMessageDialog. So it should be enough to put initializations in this case:
if (h<0){
ans = "error";
Pb = 0;
Tb = 0;
Lb = 0;
Hb = 0;
}
A better way would be to throw an exception here (and catch it later), but if you didn't yet learn about exceptions, do it first the simple way.
Unrelated to your current problem, but your program could be written quite nicer without the long "if-then-else-if-..." statement using arrays like this:
// minima of the intervals
double[] Hbs = { 0.0, 11000.0, 20000.0, 32000.0, 47000.0, 51000.0, 71000.0 };
// parameters for each interval
double[] Pbs = {101325.0, 22632.1, 5474.89, 868.019, 110.906, 66.9389, 3.95642 };
double[] Tbs = { 288.15, 216.65, 216.65, 228.65, 270.65, 270.65, 214.65 };
double[] Lbs = { -0.0065, 0.0, 0.001, 0.0028, 0.0, -0.0028, -0.002 };
int h = ...
if(h < 0) {
JOptionPane.showMessageDialog(null, "Don't use negative heights! (like " + h + ")", JOprionPane.ERROR_MESSAGE);
return;
}
// find out in which interval is our height
int i = Hbs.length-1;
while(h < Hbs[i]) {
i--;
}
double Hb = Hbs[i], Pb = Pbs[i], Tb = Tbs[i], Lb = Lbs[i];
double exp = ((-g0 * M * (h-Hb))/R * Tb);
double press = Pb*Math.exp(exp);
JOptionPane.showMessageDialog(null, "The answer is " +press+" Pascals", "Barometric Formula", JOptionPane.PLAIN_MESSAGE);
This avoids the uninitialized variable problem by returning early in case of an error.
double Pb, Tb, Lb, Hb;
change to
double Pb =0.0, Tb = 0.0, Lb = 0.0, Hb
= 0.0;
Related
I have a problem running this java code that simulates the work of a CPU.It serves processes using round robin method . I got the code from a reference and it is exactly what i need but unfortunately its not running and throws this exception :
Exception in thread "main" java.lang.NoClassDefFoundError: optimization/Lmder_fcn
at umontreal.iro.lecuyer.probdist.StudentDist.inverseF(StudentDist.java:278)
at umontreal.iro.lecuyer.stat.Tally.confidenceIntervalStudent(Tally.java:294)
at umontreal.iro.lecuyer.stat.Tally.formatCIStudent(Tally.java:359)
at umontreal.iro.lecuyer.stat.Tally.report(Tally.java:497)
here is the code :
package timeshared;
import umontreal.iro.lecuyer.simevents.*;
import umontreal.iro.lecuyer.simprocs.*;
import umontreal.iro.lecuyer.rng.*;
import umontreal.iro.lecuyer.randvar.*;
import umontreal.iro.lecuyer.stat.Tally;
import java.io.*;
public class RoundRobinQueue {
int NumberOfTermainals = 20; // Number of terminals.
double q; // Quantum size.
double overhead = 0.001; // Amount of overhead (h).
double meanThinkingTime = 5.0; // Mean thinking time.
double alpha = 0.5; // Parameters of the Weibull service times.
double lambda = 1.0; // ''
double delta = 0.0; // ''
int N = 1100; // Total number of tasks to simulate.
int N0 = 100; // Number of tasks for warmup.
int NumberOfTasks; // Number of tasks ended so far.
RandomStream streamThink = new MRG32k3a();
RandomVariateGen genThink = new ExponentialGen(streamThink, 1.0 / meanThinkingTime);
RandomStream streamServ = new MRG32k3a("Gen. for service requirements");
RandomVariateGen genServ = new WeibullGen(streamServ, alpha, lambda, delta);
Resource server = new Resource(1, "The server");
Tally meanInRep = new Tally("Average for current run");
Tally statDiff = new Tally("Diff. on mean response times");
class Terminal extends SimProcess {
public void actions() {
double arrivTime; // Arrival time of current request.
double timeNeeded; // Server's time still needed for it.
while (NumberOfTasks < N) {
delay(genThink.nextDouble());
arrivTime = Sim.time();
timeNeeded = genServ.nextDouble();
while (timeNeeded > q) {
server.request(1);
delay(q + overhead);
timeNeeded -= q;
server.release(1);
}
server.request(1); // Here, timeNeeded <= q.
delay(timeNeeded + overhead);
server.release(1);
NumberOfTasks++;
if (NumberOfTasks > N0) meanInRep.add(Sim.time() - arrivTime);
// Take the observation if warmup is over.
}
Sim.stop(); // N tasks have now completed.
}
}
private void simulOneRun() {
SimProcess.init();
server.init();
meanInRep.init();
NumberOfTasks = 0;
for (int i = 1; i <= NumberOfTermainals; i++)
new Terminal().schedule(0.0);
Sim.start();
}
// Simulate numRuns pairs of runs and prints a confidence interval
// on the difference of perf. for q sizes q1 and q2.
public void simulateConfigs(double numRuns, double q1, double q2) {
double mean1; // To memorize average for first configuration.
for (int rep = 0; rep < numRuns; rep++) {
q = q1;
simulOneRun();
mean1 = meanInRep.average();
streamThink.resetStartSubstream();
streamServ.resetStartSubstream();
q = q2;
simulOneRun();
statDiff.add(mean1 - meanInRep.average());
streamThink.resetNextSubstream();
streamServ.resetNextSubstream();
}
statDiff.setConfidenceIntervalStudent();
System.out.println(statDiff.report(0.9, 3));
}
public static void main(String[] args) {
new RoundRobinQueue().simulateConfigs(10, 0.1, 0.2);
}
}
You are missing couple of jar files in your classpath. From the documentation it looks like you would need the following jars.
http://www-labs.iro.umontreal.ca/~simardr/ssj/examples/examples.pdf
colt.jar,Blas.jar,optimization.jar ( this one in particular for your problem),jfreechart-.jar and jcommon-.jar
i fixed the problem , the program needed an optimization library here
to work , i added the jar file and it worked fine
I'm writing a java that I want to use to be able to calculate things like Entropy, Joint Entropy, Conditional Entropy, etc. when given a data set. The class in question is below:
public class Entropy {
private Frequency<String> iFrequency = new Frequency<String>();
private Frequency<String> rFrequency = new Frequency<String>();
Entropy(){
super();
}
public void setInterestedFrequency(List<String> interestedFrequency){
for(String s: interestedFrequency){
this.iFrequency.addValue(s);
}
}
public void setReducingFrequency(List<String> reducingFrequency){
for(String s:reducingFrequency){
this.rFrequency.addValue(s);
}
}
private double log(double num, int base){
return Math.log(num)/Math.log(base);
}
public double entropy(List<String> data){
double entropy = 0.0;
double prob = 0.0;
Frequency<String> frequency = new Frequency<String>();
for(String s:data){
frequency.addValue(s);
}
String[] keys = frequency.getKeys();
for(int i=0;i<keys.length;i++){
prob = frequency.getPct(keys[i]);
entropy = entropy - prob * log(prob,2);
}
return entropy;
}
/*
* return conditional probability of P(interestedClass|reducingClass)
* */
public double conditionalProbability(List<String> interestedSet,
List<String> reducingSet,
String interestedClass,
String reducingClass){
List<Integer> conditionalData = new LinkedList<Integer>();
if(iFrequency.getKeys().length==0){
this.setInterestedFrequency(interestedSet);
}
if(rFrequency.getKeys().length==0){
this.setReducingFrequency(reducingSet);
}
for(int i = 0;i<reducingSet.size();i++){
if(reducingSet.get(i).equalsIgnoreCase(reducingClass)){
if(interestedSet.get(i).equalsIgnoreCase(interestedClass)){
conditionalData.add(i);
}
}
}
int numerator = conditionalData.size();
int denominator = this.rFrequency.getNum(reducingClass);
return (double)numerator/denominator;
}
public double jointEntropy(List<String> set1, List<String> set2){
String[] set1Keys;
String[] set2Keys;
Double prob1;
Double prob2;
Double entropy = 0.0;
if(this.iFrequency.getKeys().length==0){
this.setInterestedFrequency(set1);
}
if(this.rFrequency.getKeys().length==0){
this.setReducingFrequency(set2);
}
set1Keys = this.iFrequency.getKeys();
set2Keys = this.rFrequency.getKeys();
for(int i=0;i<set1Keys.length;i++){
for(int j=0;j<set2Keys.length;j++){
prob1 = iFrequency.getPct(set1Keys[i]);
prob2 = rFrequency.getPct(set2Keys[j]);
entropy = entropy - (prob1*prob2)*log((prob1*prob2),2);
}
}
return entropy;
}
public double conditionalEntropy(List<String> interestedSet, List<String> reducingSet){
double jointEntropy = jointEntropy(interestedSet,reducingSet);
double reducingEntropyX = entropy(reducingSet);
double conEntYgivenX = jointEntropy - reducingEntropyX;
return conEntYgivenX;
}
For the past few days I've been trying to figure out why my Entropy calculation is almost always exactly the same as my calculation for conditional entropy.
I'm using the following formulas:
H(X) = - Sigma from x=1 to x=n p(x)*log(p(x))
H(XY) = - Sigma from x=1 to x=n,y=1 to y=m (p(x)*p(y)) * log(p(x)*p(y))
H(X|Y) = H(XY) - H(X)
The values that I get for my Entropy and Conditional Entropy are almost the same.
With the data set that I'm using for testing I get the following values:
#Test
public void testEntropy(){
FileHelper fileHelper = new FileHelper();
List<String> lines = fileHelper.readFileToMemory("");
Data freshData = fileHelper.parseCSVData(lines);
LinkedList<String> headersToChange = new LinkedList<String>();
headersToChange.add("lwt");
Data discreteData = freshData.discretize(freshData.getData(),headersToChange,1,10);
Entropy entropy = new Entropy();
Double result = entropy.entropy(discreteData.getData().get("lwt"));
assertEquals(2.48,result,.006);
}
#Test
public void testConditionalProbability(){
FileHelper fileHelper = new FileHelper();
List<String> lines = fileHelper.readFileToMemory("");
Data freshData = fileHelper.parseCSVData(lines);
LinkedList<String> headersToChange = new LinkedList<String>();
headersToChange.add("age");
headersToChange.add("lwt");
Data discreteData = freshData.discretize(freshData.getData(), headersToChange, 1, 10);
Entropy entropy = new Entropy();
double conditionalProb = entropy.conditionalProbability(discreteData.getData().get("lwt"),discreteData.getData().get("age"),"4","6");
assertEquals(.1,conditionalProb,.005);
}
#Test
public void testJointEntropy(){
FileHelper fileHelper = new FileHelper();
List<String> lines = fileHelper.readFileToMemory("");
Data freshData = fileHelper.parseCSVData(lines);
LinkedList<String> headersToChange = new LinkedList<String>();
headersToChange.add("age");
headersToChange.add("lwt");
Data discreteData = freshData.discretize(freshData.getData(), headersToChange, 1, 10);
Entropy entropy = new Entropy();
double jointEntropy = entropy.jointEntropy(discreteData.getData().get("lwt"),discreteData.getData().get("age"));
assertEquals(5.05,jointEntropy,.006);
}
#Test
public void testSpecifiedConditionalEntropy(){
FileHelper fileHelper = new FileHelper();
List<String> lines = fileHelper.readFileToMemory("");
Data freshData = fileHelper.parseCSVData(lines);
LinkedList<String> headersToChange = new LinkedList<String>();
headersToChange.add("age");
headersToChange.add("lwt");
Data discreteData = freshData.discretize(freshData.getData(), headersToChange, 1, 10);
Entropy entropy = new Entropy();
double specCondiEntropy = entropy.specifiedConditionalEntropy(discreteData.getData().get("lwt"),discreteData.getData().get("age"),"4","6");
assertEquals(.332,specCondiEntropy,.005);
}
#Test
public void testConditionalEntropy(){
FileHelper fileHelper = new FileHelper();
List<String> lines = fileHelper.readFileToMemory("");
Data freshData = fileHelper.parseCSVData(lines);
LinkedList<String> headersToChange = new LinkedList<String>();
headersToChange.add("age");
headersToChange.add("lwt");
Data discreteData = freshData.discretize(freshData.getData(), headersToChange, 1, 10);
Entropy entropy = new Entropy();
Double result = entropy.conditionalEntropy(discreteData.getData().get("lwt"),discreteData.getData().get("age"));
assertEquals(2.47,result,.006);
}
Everything compiles correctly but I'm pretty sure that my calculations for the conditional entropy are incorrect, but I'm not sure where I'm making a mistake.
The values that are in the unit tests are the values that I'm currently getting. They are the same as the output from the above functions.
At one point I was also using the following to do testing:
List<String> survived = Arrays.asList("1","0","1","1","0","1","0","0","0","1","0","1","0","0","1");
List<String> sex = Arrays.asList("0","1","0","1","1","0","0","1","1","0","1","0","0","1","1");
Where male = 1 and survived = 1. I then used this to calculate
double result = entropy.entropy(survived);
assertEquals(.996,result,.006);
as well as
double jointEntropy = entropy.jointEntropy(survived,sex);
assertEquals(1.99,jointEntropy,.006);
I also checked my work by calculating the values by hand. You can see an image here. Since my code was giving me the same values that I got when I did the problem by hand and since the other functions were pretty simple and just used the entropy/joint entropy functions I assumed that everything was fine.
However, something is going wrong. Below are two more functions that I wrote to calculate information gain and the symmetrical uncertainty of a set.
public double informationGain(List<String> interestedSet, List<String> reducingSet){
double entropy = entropy(interestedSet);
double conditionalEntropy = conditionalEntropy(interestedSet,reducingSet);
double infoGain = entropy - conditionalEntropy;
return infoGain;
}
public double symmetricalUncertainty(List<String> interestedSet, List<String> reducingSet){
double infoGain = informationGain(interestedSet,reducingSet);
double intSet = entropy(interestedSet);
double redSet = entropy(reducingSet);
double symUnc = 2 * ( infoGain/ (intSet+redSet) );
return symUnc;
}
The original survive/sex set that I used gave me an answer that was slightly negative. But since it was only negative by .000000000000002 I just assumed that it was a rounding error. When I tried to run my program, none of the values that I got for symmetrical uncertainty made any sense.
tldr; Your calculation for H(X,Y) apparently assumes that X and Y are independent, which results in H(X,Y) = H(X) + H(Y), which in turn results in your H(X|Y) being equal to H(X).
Is this your problem? If so, then use the correct formula for the joint entropy of X and Y (taken from Wikipedia):
You get your wrong one by substituting P(X,Y) = P(X)P(Y), which assumes that both variables are independent.
If both variables are independent, then indeed H(X|Y) = H(X) holds, because Y doesn't tell you anything about X, and consequently knowing Y doesn't decrease the entropy of X.
For calculating Entropy of single vector you can use below function
Function<List<Double>, Double> entropy =
x-> {
double sum= x.stream().mapToDouble(Double::doubleValue).sum();
return - x.stream()
.map(y->y/sum)
.map(y->y*Math.log(y))
.mapToDouble(Double::doubleValue)
.sum();
};
As an example using vector [1 2 3] would get you a result of 1.0114
double H = new Entropy().entropy.apply(Arrays.asList(new Double[] { 1.0, 2.0, 3.0 }));
System.out.println("Entropy H = "+ H);
I wrote a physical simulation about gravitational force between two planets.It worked perfectly fine so I decided to take it to a new level and rewrote it using arrays and five planets(circles).But my code gives strange and never the same error. I get either NullPointerException error or the VM error when intializing the sketch(No description just the "Vm error couldn't initialize skecth" and the "see help and troubleshoot" bullsh*t) The program uses a txt file to read in data(double-checked and it works fine).
My Array names and descriptions are
PVector - Pos stands for Position
PVector - Vel stands for Velocity
PVector - Acc stands for Acceleration
PVector - Dist stands for Distance
PVector - Dir stands for Direction
float - Mass stands for Mass
My code:
public PVector[] Pos = new PVector[5];
public PVector[] Acc = new PVector[5];
public PVector[] Vel = new PVector[5];
public PVector[] Dist = new PVector[5];
public PVector[] Dir = new PVector[5];
public float[] Mass = new float[5];
void setup(){
String Data[] = loadStrings("Data.txt");
size(800,800);
for(int g = 0;g < 5;g++){
Pos[g] = new PVector(float(Data[g+1]),float(Data[g+6]));
Vel[g] = new PVector(float(Data[g+12]),float(Data[g+17]));
Mass[g] = float(Data[g+23]);
}
}
void draw(){
for (int i = 0;i < 5;i++){
for (int f = 0;f < 5;f++){
if(i !=f){
if(Pos[i].x < Pos[f].x){Dir[f].x = 1;Dist[f].x = (Pos[f].x - Pos[i].x);}else{ // I get the error here
if(Pos[i].x > Pos[f].x){Dir[f].x = -1;Dist[f].x = (Pos[i].x - Pos[f].x);}else{
if(Pos[i].x == Pos[f].x){Dir[f].x = 0;Dist[f].x = 0;}}}
if(Pos[i].y < Pos[f].y){Dir[f].y = 1;Dist[f].y = (Pos[f].y - Pos[i].y);}else{
if(Pos[i].y > Pos[f].y){Dir[f].y = -1;Dist[f].y = (Pos[i].y - Pos[f].y);}else{
if(Pos[i].y == Pos[f].y){Dir[f].y = 0;Dist[f].y = 0;}}}
if ((Dist[f].x != 0)){
Acc[i].x+=((6*((Mass[i]*Mass[f])/Dist[f].magSq())/10000000)/Mass[i])*Dir[f].x;// *6/1000000 is MY G constant
}
if ((Dist[f].y != 0)){
Acc[i].y+=((6*((Mass[i]*Mass[f])/Dist[f].magSq())/10000000)/Mass[i])*Dir[f].y;
}
}
}
Vel[i].x = Vel[i].x + Acc[i].x;
Vel[i].y = Vel[i].y + Acc[i].y;
Pos[i].x = Pos[i].x + Vel[i].x;
Pos[i].y = Pos[i].y + Vel[i].y;
ellipse(Pos[i].x,Pos[i].y,10,10);
}
}
You create array of PVectors of size 5 here : public PVector[] Dir = new PVector[5]; . In this moment, it has null five times for indexes 0-4 in it.
Because you do not create new PVectors in this array, when you try to access variable x in here Dir[f].x, you got error, because Dir[f] is null and you cant access variable x of null -> NullPointerException.
In this part you are instantizing some arrays
for(int g = 0;g < 5;g++){
Pos[g] = new PVector(float(Data[g+1]),float(Data[g+6]));
Vel[g] = new PVector(float(Data[g+12]),float(Data[g+17]));
Mass[g] = float(Data[g+23]);
}
You should add instantizing also for Dir, Acc and Dist
Note also, that you are working with objects, not with primitive data types. null is not same as new PVector(0,0)
Also from "design" point of view, using arrays this way is NOT good approach. You should create your own class Planet, where each planet holds information about its properties and in your main class you handle interaction between them.
How to create "empty" or "zero" variables instead of nulls? Just create them :)
for(int g = 0;g < 5;g++){
Pos[g] = new PVector(float(Data[g+1]),float(Data[g+6]));
Vel[g] = new PVector(float(Data[g+12]),float(Data[g+17]));
Mass[g] = float(Data[g+23]);
Dir[g] = new PVector(0,0);
Acc[g] = new PVector(0,0);
Dist[g] = new PVector(0,0);
}
PS : I do not how exactly is this class implemented, using new PVector() or new PVector(0) instead of new PVector(0,0) may also work.
Right now I'm working on a GUI that will calculate kinematic values based on what the user enters into a text field. I created a private inner class with values of type Double (not double), and then created a method to get a value based on values given. For example, this returns initial velocity:
public Double getInitialVelocity(Double vf, Double a, Double ti, Double tf) {
deltaT = deltaT(tf, ti);
initialVelocity = vf - (a * deltaT);
df.format(initialVelocity);
return initialVelocity;
}
The problem appears when I tried to test this method. I set up new doubles, and use getInitialVelocity in my main class:
Kinematics test = new Kinematics(); // creates object from inner class
Double vf = 1.0, a = 2.0, ti = 0.5, tf = 1.5;
test.getInitialVelocity(vf, a, ti, tf);
When I run this to test, I get this error:
Static Error: No method in Kinematics with name 'getInitialVelocity' matches this invocation
Arguments: (Double, Double, Double, Double)
Candidate signatures: double getInitialVelocity()
Does anyone know how to properly do this? I need to use type Double because I am comparing values given to null and then using the appropriate formula based on which values are null. Also, when converting from a String, should I just use Double.parseDouble(textField.getText()); ?
Edit 1: Here are the relevant parts of my class:
Private inner class (Kinematics):
private class Kinematics {
private Double initialVelocity, finalVelocity, acceleration, timeFinal, timeInitial;
private Double deltaT;
// constructor
public Kinematics() {
}
public Double deltaT(Double tf, Double ti) {
if(!(tf == null && ti == null)){
deltaT = tf - ti;
} return deltaT;
}
public Double getInitialVelocity(Double vf, Double a, Double ti, Double tf) {
deltaT = deltaT(tf, ti);
initialVelocity = vf - (a * deltaT);
df.format(initialVelocity);
return initialVelocity;
}
In my main class (KinematicsPanel), I have:
Kinematics values = new Kinematics();
viLabel = new JLabel("Initial Velocity: ");
viText = new JTextField(1);
vfLabel = new JLabel("Final Velocity: ");
vfText = new JTextField(1);
aLabel = new JLabel("Acceleration: ");
aText = new JTextField(1);
tiLabel = new JLabel("Initial Time: ");
tiText = new JTextField(1);
tfLabel = new JLabel("Final Time: ");
tfText = new JTextField(1);
// compute button & result
compute = new JButton("Compute");
compute.addActionListener(this);
result = new JTextField(2);
result.setEditable(false); // can not be edited
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
// parse each string to a value
Double vf = 0.0, a = 0.0, ti = 0.0, tf = 0.0;
if(vfText != null) {vf = Double.parseDouble(vfText.getText());}
if(aText != null) {a = Double.parseDouble(aText.getText());}
if(tiText != null) {ti = Double.parseDouble(tiText.getText());}
if(tfText != null) {tf = Double.parseDouble(tfText.getText());}
if(action.equals("Compute")) {
if(viText == null) { // get initial velocity
// get values
values.getInitialVelocity(vf, a, ti, tf);
System.out.println(values.toString()); // to test
result.setText(values.toString());
}
}
As of right now, this does nothing which is why I tested the method in the interactions pane in Dr.Java.
Edit2: The format function being used is in the main class:
DecimalFormat df = new DecimalFormat("#.00");
Its all ok with your code, which compiler are you using?
The method getInitialVelocity are in the class Kinematics?
it looks , you are using jdk 1.4 or lower one, there autoboxing is not supported.
so it can not convert Double to double. but that should give you a compile time
error if you are using IDE like eclipse.
OR
may be the method you are calling has different signature.
try to check the jdk version and post whole class if above one does no solve your problem.
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.