Problems updating labels using variables from if-statements (Java) - java

First of all, I´m new to both Java and programming (except Matlab), so simple answers is much appreciated :-).
I'm trying to create a temperature converter (with GUI) and I need to update some labels. That worked fine in the beginning, but now I have to use values from inside an if-statement. This results in an error where I try to update the labels:
tempKelvin cannot be resolved to a variable
All the action happens when the "Convert" button is clicked, the code for this is here:
// Create and add convert button
JButton fahrenheitButton = new JButton("Convert");
fahrenheitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Check if input is of type double and perform action
if (isNumber(tempTextField.getText())) {
double inputTemp = Double.parseDouble(tempTextField.getText());
// Convert from Kelvin
if (((String) unitDropdown.getSelectedItem()).equals("Kelvin")) {
int tempKelvin = (int) (inputTemp);
int tempCelcius = (int) (inputTemp - 273.15);
int tempFahrenheit = (int) ((inputTemp - 273.15) * (9/5) + 32);
// Convert from Celsius
} else if (((String) unitDropdown.getSelectedItem()).equals("Celsius")) {
int tempKelvin = (int) (inputTemp + 273.15);
int tempCelcius = (int) (inputTemp);
int tempFahrenheit = (int) (inputTemp * (9/5) + 32);
// Convert from Fahrenheit
} else if (((String) unitDropdown.getSelectedItem()).equals("Fahrenheit")) {
int tempKelvin = (int) ((inputTemp - 32) * (5/9) + 273.15);
int tempCelcius = (int) ((inputTemp - 32) * (5/9));
int tempFahrenheit = (int) ((inputTemp - 273.15) * (9/5) + 32);
// If none of the above was selected, it's an error...
} else {
int tempKelvin = 0;
int tempCelcius = 0;
int tempFahrenheit = 0;
warningLabel.setText("Oops, this doesn't look good!");
}
// Update labels
kelvinLabel.setText(tempKelvin + " K");
celsiusLabel.setText(tempCelcius + " C");
fahrenheitLabel.setText(tempFahrenheit + " F");
warningLabel.setText("");
} else {
warningLabel.setText("Input must be numeric!");
}
}
});
fahrenheitButton.setBounds(20, 45, 89, 23);
contentPane.add(fahrenheitButton);
Any help would be greatly appreciated, thanks!!

YOu need to define int tempKelvin outside the if statements and reuse it as mentioned here:
// Create and add convert button
JButton fahrenheitButton = new JButton("Convert");
fahrenheitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// Check if input is of type double and perform action
if (isNumber(tempTextField.getText())) {
double inputTemp = Double.parseDouble(tempTextField.getText());
int tempKelvin = -1;
int tempCelcius = -1;
int tempFahrenheit = -1;
// Convert from Kelvin
if (((String) unitDropdown.getSelectedItem()).equals("Kelvin")) {
tempKelvin = (int) (inputTemp);
tempCelcius = (int) (inputTemp - 273.15);
tempFahrenheit = (int) ((inputTemp - 273.15) * (9/5) + 32);
// Convert from Celsius
} else if (((String) unitDropdown.getSelectedItem()).equals("Celsius")) {
tempKelvin = (int) (inputTemp + 273.15);
tempCelcius = (int) (inputTemp);
tempFahrenheit = (int) (inputTemp * (9/5) + 32);
// Convert from Fahrenheit
} else if (((String) unitDropdown.getSelectedItem()).equals("Fahrenheit")) {
tempKelvin = (int) ((inputTemp - 32) * (5/9) + 273.15);
tempCelcius = (int) ((inputTemp - 32) * (5/9));
tempFahrenheit = (int) ((inputTemp - 273.15) * (9/5) + 32);
// If none of the above was selected, it's an error...
} else {
tempKelvin = 0;
tempCelcius = 0;
tempFahrenheit = 0;
warningLabel.setText("Oops, this doesn't look good!");
}
// Update labels
kelvinLabel.setText(tempKelvin + " K");
celsiusLabel.setText(tempCelcius + " C");
fahrenheitLabel.setText(tempFahrenheit + " F");
warningLabel.setText("");
} else {
warningLabel.setText("Input must be numeric!");
}
}
});
fahrenheitButton.setBounds(20, 45, 89, 23);
contentPane.add(fahrenheitButton);

Your problem is you create a new temp variable in every if [else] statement. That's why the variable doesn't exist outside these statement(s).

You're referencing the "temp" variables out of their scope.
They are declared in each statement of your if/else conditional statement, but referenced after the conditional statement is closed (under comment "update labels").
One solution is to declare your variables before the conditional statement and only assign them in the conditions.

Your magic word is: Scope.
Because your variable is defined inside your if-statement, it actually 'dissapears' after that statement ('scope' if you will) - ends.
Just extract your variable to the most-outer scope you want to refer to it in. Good luck!

You better do this:
int tempKelvin = 0;
int tempCelcius = 0;
int tempFahrenheit = 0;
if(condition1){
///
}else if(condition2){
//
}else if(condition3){
//
}else{
//
}
inside if, you don't need to re-declare int function, just tempKelvin=....;

Related

Java Convert double to int

I have this code, and the input in the textfield is 50, so its output should be 25,
but there is a error, because no output
button_1.addActionListener(new ActionListener() {
String tfg = textField.getText().toString();
String tfc = textField.getText();
public void actionPerformed(ActionEvent e) {
if(textField.getText().toString().equals("0") ||
textField.getText().toString().equals("") ||
textField.getText().toString().equals(" ") ||
textField.getText().toString().matches("[a-zA-Z]+")) {
JOptionPane.showMessageDialog(Cow.this,
"Tree Amount Should Be 1 or More",
"Invalid Tree Amount",
JOptionPane.ERROR_MESSAGE);
}
if(!tfg.equals("0")) {
try {
int tfgg = Integer.parseInt(tfc);
int trcs = tfgg * 1;
double trcp = 1 / 2;
int trcc = (int) trcp * trcs;
System.out.println(new Integer(trcc).toString());
} catch (NumberFormatException se) {
}
}
}
});
I try to convert from my php to that code, here is my php code :
$doorSeed = $mount * 1;
$doorPrice = 1 / 2;
$doorConvert = $doorPrice * $doorSeed;
echo "Treasure Chest Seed = ".$doorSeed." Price : ".$doorConvert." World Lock <br>";
int trcc = (int) trcp * trcs;
Try this instead
int trcc = (int) (trcp * trcs);
You need to cast the complete expression [(trcp * trcs)] instead of just the first variable trcp to int. The other variable in the expression trcs is of double type, so the result of the expression become double. That is why you cast the complete expression. So your end result will be int
int tfgg = Integer.parseInt(tfc.trim()); // tfc = 4; tfgg = 4;
int trcs = tfgg * 1; // trcs = 4 * 1 = 5;
double trcp = 1.0 / 2; // trcp = 0.5;
int trcc = (int) (trcp * trcs); // trcc = (0.5 * 5) = (2.5) = 2;
System.out.println(trcc); // 2;
double trcp = 1.0 / 2;
Here make at least one value as double so the expression will be evaluated as double as suggested by #tunaki.
Also you don't need this statement in your code int trcs = tfgg * 1;.
Use like this:
String tfg ;
String tfc ;
public void actionPerformed(ActionEvent e) {
tfg = textField.getText();
tfc = textField.getText();
if(textField.getText().equals("0") || textField.getText().equals("") || textField.getText().equals(" ") || textField.getText().matches("[a-zA-Z]+")) {
JOptionPane.showMessageDialog(Cow.this,
"Tree Amount Should Be 1 or More",
"Invalid Tree Amount",
JOptionPane.ERROR_MESSAGE);
}
if(!tfg.equals("0")) {
try {
int tfgg = Integer.parseInt(tfc.trim()); // tfc = 4;
int trcs = tfgg; // trcs = 4 * 1 = 5
double trcp = 1.0 / 2; // trcp = 0.5
int trcc = (int) (trcp * trcs); // trcc = (0.5 * 5) = (2.5) = 2
System.out.println("HI: "+trcc);
} catch (NumberFormatException ignored) {
}
Your problem is at this line:
double trcp = 1 / 2;
This does not result in trcp = 0.5 but trcp = 0.0, because you are dividing integer values (and so are using integer division).
You should use the following code:
double trcp = 1.0 / 2;
to force division using doubles.
Other comments:
new Integer(trcc).toString() should be replaced with String.valueOf(trcc).
Avoid using empty catch statements: at minimum, log the exception
What's the point of this line: int trcs = tfgg * 1;?
Basically you have this (int)0.5 = 0.
In your case, trcp = 0.5 and is double, so when it's cast to integer the result is 0.
And when you do (int)a + b, the true operation with parenthesis for priority here is: ((int)a)+(b), so what you have to is the following:
int trcc = (int) (trcp * trcs);
instead of the following:
int trcc = (int) trcp * trcs;

How can I translate console application to SWING framework?

I have a working class HoltWinters, which is main in my package. It is a console application. I search the one folder on my computer, read names of all the files in this folder. Then I ask the user to print the name of the file he wants to use in the programm. After it I save this name as string and use this file for the forecast.
But i need to do it via windows application. As i understand it, i need to create new java JFrame (I use NetBeans, so I've done using their constructor). I put there 1 JText field and 1 JButton. I want next things to happen when i press the button:
the text from the JText field is read and saved as String
the method HoltWinters.main is run, using String from the JText
But i don't understand how to do it at all:( I think, maybe i have some mistake in my logic or it should be done differently, but it's my first not console application and i don't know what to do:-(
That is my HoltWinters class:
package holtwinters;
import java.io.*;
import java.util.*;
import java.lang.*;
/**
St[i] = alpha * y[i] / It[i - period] + (1.0 - alpha) * (St[i - 1] + Bt[i - 1]) - overall
Bt[i] = gamma * (St[i] - St[i - 1]) + (1 - gamma) * Bt[i - 1] - trend
It[i] = beta * y[i] / St[i] + (1.0 - beta) * It[i - period] - season
Ft[i + m] = (St[i] + (m * Bt[i])) * It[i - period + m] - predictions
*/
/**
*
* #author Jane
*/
public class HoltWinters {
/**
* #param args the command line arguments
*/
/*
y - Time series data.
alpha - coeff
beta - coeff
gamma - coeff
period - 24 hours
m - future data
debug - debug values for testing
*/
public static void main( String[] args )
throws FileNotFoundException, IOException {
String path = "C:\\Users\\Jane\\Desktop";
File f = new File (path);
String[] list=f.list();
for (String str : list){
System.out.println(str);
}
BufferedReader in=new BufferedReader (new InputStreamReader(System.in));
System.out.print("Input n: ");
String sn=in.readLine();
String[] ary = sn.split(" ");
String name = null;
for(String file1: list) {
for (String ary1: ary) {
if (ary1.equals(file1)) {
System.out.println("found!");
name = sn;
}
}
}
File file = new File( path+"\\"+name );
BufferedReader br = new BufferedReader (
new InputStreamReader(
new FileInputStream( file ), "UTF-8"
)
);
String line = null;
while ((line = br.readLine()) != null) {
try {
Long y = Long.valueOf(line);
// System.out.println(y);
} catch (NumberFormatException e) {
System.err.println("Неверный формат строки!");
}
}
// long data = Long.valueOf(line);
// int change = (int) data;
// long [] y = new long [change];
int period = 24;
int m = 5;
long[] y = new long[144];
try {
Scanner scanner = new Scanner(new File(path+"\\"+name));
int i = 0;
while (scanner.hasNextLong()) {
y[i] = scanner.nextLong();
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
double sum_origin = 0;
int k=0;
do {
sum_origin = sum_origin + y[k];
k++;
} while (k<24);
//searching for alpha
double alpha = 0.01;
double a = 0.01;
double x=sum_origin;
double q;
do {
double beta = 0.3;
double gamma = 0.3;
double[] prediction = HoltWinters.forecast(y, a, beta, gamma,
period, m);
double sum_pre = sum(prediction);
q = sum_origin - sum_pre;
if (q<=x) {
x=q;
alpha = a;
}
a = a +0.01;
} while (a<0.99);
//searching for beta
double beta = 0.01;
double b = 0.01;
double x1=1000000;
double q1;
do {
double gamma = 0.3;
double[] prediction = HoltWinters.forecast(y, alpha, b, gamma,
period, m);
double sum_pre = sum(prediction);
q1 = sum_origin - sum_pre;
if (q1<=x1) {
x1=q1;
beta = b;
}
b = b +0.01;
} while (b<0.99);
//searching for gamma
double gamma = 0.01;
double g = 0.01;
double x2=1000000;
double q2;
do {
double[] prediction = HoltWinters.forecast(y, alpha, beta, g,
period, m);
double sum_pre = sum(prediction);
q2 = sum_origin - sum_pre;
if (q2<=x2) {
x2=q2;
gamma = g;
}
g = g +0.01;
} while (g<0.99);
System.out.println(alpha);
System.out.println(beta);
System.out.println(gamma);
double[] prediction = HoltWinters.forecast(y, alpha, beta, gamma,
period, m);
for(int i = period; i <= prediction.length - 1; i++) {
System.out.println(prediction[i] + " ");
}
br.close();
File flt = new File("C:\\Users\\Jane\\Desktop\\003003_prediction.txt");
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter(flt)));
for(int i = period; i <= prediction.length - 1; i++) {
out.println(prediction[i] + " ");
}
out.flush();
}
public static double sum(double...values) {
double result = 0;
for (double value:values)
result += value;
return result;
}
public static double[] forecast(long[] y, double alpha, double beta,
double gamma, int period, int m, boolean debug) {
validateArguments(y, alpha, beta, gamma, period, m);
int seasons = y.length / period;
double a0 = calculateInitialLevel(y, period);
double b0 = calculateInitialTrend(y, period);
double[] initialSeasonalIndices = calculateSeasonalIndices(y, period,
seasons);
if (debug) {
System.out.println(String.format(
"Total observations: %d, Seasons %d, Periods %d", y.length,
seasons, period));
System.out.println("Initial level value a0: " + a0);
System.out.println("Initial trend value b0: " + b0);
printArray("Seasonal Indices: ", initialSeasonalIndices);
}
double[] forecast = calculateHoltWinters(y, a0, b0, alpha, beta, gamma,
initialSeasonalIndices, period, m, debug);
if (debug) {
printArray("Forecast", forecast);
}
return forecast;
}
public static double[] forecast(long[] y, double alpha, double beta,
double gamma, int period, int m) {
return forecast(y, alpha, beta, gamma, period, m, false);
}
/**
validate input
*/
private static void validateArguments(long[] y, double alpha, double beta,
double gamma, int period, int m) {
if (y == null) {
throw new IllegalArgumentException("Value of y should be not null");
}
if(m <= 0){
throw new IllegalArgumentException("Value of m must be greater than 0.");
}
if(m > period){
throw new IllegalArgumentException("Value of m must be <= period.");
}
if((alpha < 0.0) || (alpha > 1.0)){
throw new IllegalArgumentException("Value of Alpha should satisfy 0.0 <= alpha <= 1.0");
}
if((beta < 0.0) || (beta > 1.0)){
throw new IllegalArgumentException("Value of Beta should satisfy 0.0 <= beta <= 1.0");
}
if((gamma < 0.0) || (gamma > 1.0)){
throw new IllegalArgumentException("Value of Gamma should satisfy 0.0 <= gamma <= 1.0");
}
}
/**
the Holt-Winters equations
*/
private static double[] calculateHoltWinters(long[] y, double a0, double b0,
double alpha, double beta, double gamma,
double[] initialSeasonalIndices, int period, int m, boolean debug) {
double[] St = new double[y.length];
double[] Bt = new double[y.length];
double[] It = new double[y.length];
double[] Ft = new double[y.length + m];
// Initialize base values
St[1] = a0;
Bt[1] = b0;
for (int i = 0; i < period; i++) {
It[i] = initialSeasonalIndices[i];
}
// Start calculations
for (int i = 2; i < y.length; i++) {
// Calculate overall smoothing
if ((((i - period) >= 0) & (It[i]!=0))) {
St[i] = alpha * y[i] / It[i - period] + (1.0 - alpha)
* (St[i - 1] + Bt[i - 1]);
}
else {
St[i] = alpha * y[i] + (1.0 - alpha) * (St[i - 1] + Bt[i - 1]);
}
// Calculate trend smoothing
Bt[i] = gamma * (St[i] - St[i - 1]) + (1 - gamma) * Bt[i - 1];
// Calculate seasonal smoothing
if ((i - period) >= 0) {
It[i] = beta * y[i] / St[i] + (1.0 - beta) * It[i - period];
}
// Calculate forecast
if (((i + m) >= period)) {
Ft[i + m] = Math.abs(((St[i] + (m * Bt[i])) * It[i - period + m])*(-1));
}
if (debug) {
System.out.println(String.format(
"i = %d, y = %d, S = %f, Bt = %f, It = %f, F = %f", i,
y[i], St[i], Bt[i], It[i], Ft[i]));
}
}
return Ft;
}
/**
Initial Level value - St[1]
*/
public static double calculateInitialLevel(long[] y, int period) {
double sum = 0;
for (int i = 0; i < 24; i++) {
sum += (y[i]);
}
return sum / (period*period);
}
/**
Initial trend - Bt[1]
*/
public static double calculateInitialTrend(long[] y, int period) {
double sum = 0;
for (int i = 0; i < period; i++) {
sum += Math.abs((y[period + i] - y[i]));
}
return sum / (period * period);
}
/**
Seasonal Indices.
*/
public static double[] calculateSeasonalIndices(long[] y, int period,
int seasons) {
double[] seasonalAverage = new double[seasons];
double[] seasonalIndices = new double[period];
double[] averagedObservations = new double[y.length];
for (int i = 0; i < seasons; i++) {
for (int j = 0; j < period; j++) {
seasonalAverage[i] += y[(i * period) + j];
}
seasonalAverage[i] /= period;
}
for (int i = 0; i < seasons; i++) {
for (int j = 0; j < period; j++) {
averagedObservations[(i * period) + j] = y[(i * period) + j]
/ seasonalAverage[i];
}
}
for (int i = 0; i < period; i++) {
for (int j = 0; j < seasons; j++) {
seasonalIndices[i] += averagedObservations[(j * period) + i];
}
seasonalIndices[i] /= seasons;
}
return seasonalIndices;
}
/**
method to print array values
*/
private static void printArray(String description, double[] data) {
System.out.println(description);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
}
}
This is JFrame
package holtwinters;
/**
*
* #author Jane
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("Введите номер банкомата");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton1.setText("Ввести");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(136, 136, 136)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(141, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println("Button pressed") ;
HoltWinters other = new HoltWinters();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
yourButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
yourButtonActionPerformed(evt);
}
});
public void yourButtonActionPerformed(java.awt.event.ActionEvent evt) {
String yourText = jTextField1.getText();
HoltWinters tempHolt = new HoltWinters();
tempHolt.methodToRun(yourText);
}
you need to change your code a lot, start with dao, model and gui layers (packages).

Java Error 'error: cannot find symbol'

I am in the process of learning Java. Below is the program that I've been trying to compile, but cannot figure out why 'x' in line 38 provides the following error: 'cannot find symbol'. Any help would be greatly appreciated.
import java.util.Scanner;
class metropolis_HW2_7 {
static int count = 0;
public static void main(String[] args) {
double a = 0.;
double b = Math.PI;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println(" Number of bins?");
int nbin = sc.nextInt();
if (nbin < 1)
System.exit(0);
double[] bin = new double[nbin];
System.out.println(" Number of histories to run?");
int N = sc.nextInt();
double dx = (b - a) / nbin;
for (int i = 0; i < N; i++) {
if (count == 0) {
double squiggle1 = Math.PI * Math.random();
double squiggle2 = Math.PI * Math.random();
double y_1 = 2 * squiggle1 + Math.sin(squiggle1);
double y_2 = 2 * squiggle2 + Math.sin(squiggle2);
if (y_2 < y_1) {
squiggle1 = squiggle2;
double x = squiggle2;
} else {
squiggle1 = squiggle1;
double x = squiggle2 / squiggle1;
}
count++;
} else {
double squiggle1;
double x = Sample(squiggle1);
}
int binNumber = (int) ((x - a) / dx);
bin[binNumber] += 1.;
}
double x = a - dx / 2.;
for (int i = 0; i < nbin; i++) {
x += dx;
bin[i] /= N * dx;
System.out.printf(" Bin %1$5d Sample for x = %2$7.5f is %3$7.5f vs %4$7.5f Ratio (%5$f) \n", i, x, bin[i], PDF(x), bin[i] / PDF(x));
}
}
}
static double Sample(double squiggle1) {
double squiggle2 = Math.PI * Math.random();
double y_1 = 2 * squiggle1 + Math.sin(squiggle1);
double y_2 = 2 * squiggle2 + Math.sin(squiggle2);
if (y_2 < y_1) {
squiggle1 = squiggle2;
return squiggle2;
} else {
squiggle1 = squiggle1;
return squiggle2 / squiggle1;
}
count++;
}
static double PDF(double x) {
return (2 * x + Math.sin(x)) / (Math.pow(Math.PI, 2) + 2);
}
}
Variables only exist inside the scope (between { and }) they're declared in. You have three different variables called x, and none of them exist when the line int binNumber=(int)((x-a)/dx); is executed.
Declare a variable outside the if statements, and then assign it inside it, something like this: (I've removed most of your code to make this example clearer; obvious you still need it)
double x;
if (count==0) {
if (y_2<y_1) {
x=squiggle2;
} else {
x=squiggle2/squiggle1;
}
} else {
x=Sample(squiggle1);
}
int binNumber=(int)((x-a)/dx);
Declare double x variable globally.You are declared in else part thats why it could not find the variable.
Scope variable Example:
int a = 80; // Create a global variable "a"
void setup() {
size(640, 360);
background(0);
stroke(255);
noLoop();
}
void draw() {
// Draw a line using the global variable "a"
line(a, 0, a, height);
// Create a new variable "a" local to the for() statement
for (int a = 120; a < 200; a += 2) {
line(a, 0, a, height);
}
// Create a new variable "a" local to the draw() function
int a = 300;
// Draw a line using the new local variable "a"
line(a, 0, a, height);
// Make a call to the custom function drawAnotherLine()
drawAnotherLine();
// Make a call to the custom function setYetAnotherLine()
drawYetAnotherLine();
}
void drawAnotherLine() {
// Create a new variable "a" local to this method
int a = 320;
// Draw a line using the local variable "a"
line(a, 0, a, height);
}
void drawYetAnotherLine() {
// Because no new local variable "a" is set,
// this line draws using the original global
// variable "a", which is set to the value 80.
line(a+2, 0, a+2, height);
}
The variable x is not declared in the scope in which it is used at that line. You are defining and assigning the double x inside two different if-blocks. Try declaring the variable in a broader scope (say, before the if-block, then assign it locally. Then it will be accessible in all 3 places.
Here's a simple example to explain what I mean:
void method()
{
if (2 > 1)
double x = 2;
else
double x = 3;
System.out.println(x); //ERROR, because x is out of scope
}
So change it to
void method()
{
double x = 0;
if (2 > 1)
x = 2;
else
x = 3;
System.out.println(x); //No error; x is referenced in the same scope in which it is declared
}

Computing area of a polygon in Java

I have a class called SimplePolygon that creates a polygon with coordinates provided by the user. I am trying to define a method to compute the area of the polygon. It's an assignment and course instructor wants us to use the following formula to compute the area.
I can use either formula. I chose the right one.
My code gives me the wrong area. I don't know what's wrong.
public class SimplePolygon implements Polygon {
protected int n; // number of vertices of the polygon
protected Point2D.Double[] vertices; // vertices[0..n-1] around the polygon
public double area() throws NonSimplePolygonException {
try
{
if(isSimple()==false)
throw new NonSimplePolygonException();
else
{
double sum = 0;
for(int i = 0; i < vertices.length - 1; i++)
if(i == 0)
sum += vertices[i].x * (vertices[i+1].y - vertices[vertices.length - 1].y);
else
sum += vertices[i].x * (vertices[i+1].y - vertices[i-1].y);
double area = 0.5 * Math.abs(sum);
return area;
}
}
catch(NonSimplePolygonException e)
{
System.out.println("The Polygon is not simple.");
}
return 0.0;
}
The following is a tester code. The polygon is a rectangle with area 2, but the output is 2.5
Point2D.Double a = new Point2D.Double(1,1);
Point2D.Double b = new Point2D.Double(3,1);
Point2D.Double c = new Point2D.Double(3,2);
Point2D.Double d = new Point2D.Double(1,2);
SimplePolygon poly = new SimplePolygon(4);
poly.vertices[0] = a;
poly.vertices[1] = b;
poly.vertices[2] = c;
poly.vertices[3] = d;
System.out.println(poly.area());
Now that you've fixed the trivial boundary case, you're missing another boundary and your loop is wrong. Corrected code with debug:
public double area()
{
double sum = 0;
for (int i = 0; i < vertices.length ; i++)
{
if (i == 0)
{
System.out.println(vertices[i].x + "x" + (vertices[i + 1].y + "-" + vertices[vertices.length - 1].y));
sum += vertices[i].x * (vertices[i + 1].y - vertices[vertices.length - 1].y);
}
else if (i == vertices.length - 1)
{
System.out.println(vertices[i].x + "x" + (vertices[0].y + "-" + vertices[i - 1].y));
sum += vertices[i].x * (vertices[0].y - vertices[i - 1].y);
}
else
{
System.out.println(vertices[i].x + "x" + (vertices[i + 1].y + "-" + vertices[i - 1].y));
sum += vertices[i].x * (vertices[i + 1].y - vertices[i - 1].y);
}
}
double area = 0.5 * Math.abs(sum);
return area;
}
There is one missing term from the sum: vertices[n-1].x * (vertices[0].y - vertices[n-2].y).
Before the edit of the question there was also a problem with the first term:
Furthermore, if i==0 the term should be vertices[i].x * (vertices[i+1].y - vertices[n-1].y).
Assuming that n is equal to vertices.length.
The simplest way to code the loop is probably:
n = vertices.length;
sum =0;
for (int i = 0; i < n; i++) {
sum += vertices[i].x * (vertices[(i + 1) % n].y - vertices[(i + n - 1) % n].y);
}
I found another way,
Add first element again into polygon array
So that we can avoid "Out of bound" case as well as many If conditions.
Here is my solution:
public class PolygonArea {
public static void main(String[] args) {
PolygonArea p = new PolygonArea();
System.out.println(p.calculateArea());
}
Point[] points = new Point[5];
public double calculateArea() {
points[0] = new Point("A", 4, 10);
points[1] = new Point("B", 9, 7);
points[2] = new Point("C", 11, 2);
points[3] = new Point("D", 2, 2);
/** Add first entry again to polygon */
points[4] = new Point("A", 4, 10);
double sum = 0.0;
for (int i = 0; i < points.length - 1; ++i) {
sum += (points[i].X * points[i + 1].Y) - (points[i + 1].X * points[i].Y);
}
return Math.abs(sum / 2);
}
class Point {
final String _ID;
final int X;
final int Y;
public Point(String id, int x, int y) {
_ID = id;
X = x;
Y = y;
}
}
}

Strange issue in converting Feet and Inches to Centimeter and Vice Versa

public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {
}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}
Above is the function for converting Feet and Inches to Centimeter.Below is the function for converting Centimeter back to Feet and Inches.
public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
I have a problem when i enter normal values like 5 Feet and 6 Inches, its converting perfectly to centimeter and again it gets converted back to 5 Feet and 6 Inches.
The Problem is when i convert 1 Feet and 1 inches or 2 Feet and 2
inches, its getting converted back to 1 Feet 2 inches and 2 Feet 3
inches.
I ran the following code
public class FeetInches{
public static void main(String[] args){
double d = convertFeetandInchesToCentimeter("1","1");
String back_again = convertCentimeterToHeight(d);
System.out.println(back_again);
}
public static double convertFeetandInchesToCentimeter(String feet, String inches) {
double heightInFeet = 0;
double heightInInches = 0;
try {
if (feet != null && feet.trim().length() != 0) {
heightInFeet = Double.parseDouble(feet);
}
if (inches != null && inches.trim().length() != 0) {
heightInInches = Double.parseDouble(inches);
}
} catch (NumberFormatException nfe) {
}
return (heightInFeet * 30.48) + (heightInInches * 2.54);
}
public static String convertCentimeterToHeight(double d) {
int feetPart = 0;
int inchesPart = 0;
if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
feetPart = (int) Math.floor((d / 2.54) / 12);
System.out.println((d / 2.54) - (feetPart * 12));
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
}
return String.format("%d' %d''", feetPart, inchesPart);
}
}
And got
1.0000000000000018
1' 2''
By using the ceiling function you are rounding up to 2 when you really want to be rounding down to 1.
I believe:
inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
Should be:
inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));
The problem is because of the way java handles floating point numbers.
inchesPart = (int) Math.ceil(Math.round((d / 2.54) - (feetPart * 12)));
or
inchesPart = (int) Math.floor((d / 2.54) - (feetPart * 12));
In case of input 2,2 the original value of inchesPart is 2.0000000000000036 -> ceil ->3
The main issue with you're code is that you're not using the same rounding function for each part :
int feetPart = (int) Math.floor((d / 2.54) / 12);
^^^^^
int inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
^^^^
You should also do the rounding before the decomposition in order to obtain consistent results :
int feetPart = ((int) Math.round(d / 2.54)) / 12;
int inchesPart = ((int) Math.round((d / 2.54)) - (feetPart * 12);
Which could be factorized to:
int inches = (int) Math.round(d / 2.54);
int feetPart = inches / 12;
int inchesPart = inches - (feetPart * 12);
Or since ( inches - ( ( inches / 12 ) * 12) ) == ( inches % 12 ):
int inches = (int) Math.round(d / 2.54);
feetPart = inches / 12;
inchesPart = inches % 12;
You can interchange Math.round with Math.floor or Math.ceil depending on the result you expect.
I know this is old may be useful for someone else (Kotlin version)
fun feetToCentimeter(feetval: String): String {
var heightInFeet = 0.0
var heightInInches = 0.0
var feet = ""
var inches = ""
if (!TextUtils.isEmpty(feetval)) {
if (feetval.contains("'")) {
feet = feetval.substring(0, feetval.indexOf("'"))
}
if (feetval.contains("\"")) {
inches = feetval.substring(feetval.indexOf("'") + 1, feetval.indexOf("\""))
}
}
try {
if (feet.trim { it <= ' ' }.isNotEmpty()) {
heightInFeet = feet.toDouble()
}
if (inches.trim { it <= ' ' }.isNotEmpty()) {
heightInInches = inches.toDouble()
}
} catch (nfe: NumberFormatException) {
}
return (((heightInFeet * 12.0) + heightInInches) * 2.54).toString()
}
fun centimeterToFeet(centemeter: String?): String {
var feetPart = 0
var inchesPart = 0
if (!TextUtils.isEmpty(centemeter)) {
val dCentimeter = java.lang.Double.valueOf(centemeter!!)
feetPart = Math.floor((dCentimeter / 2.54) / 12).toInt()
println(dCentimeter / 2.54 - feetPart * 12)
inchesPart = Math.floor((dCentimeter / 2.54) - (feetPart * 12)).toInt()
}
return String.format("%d' %d\"", feetPart, inchesPart)
}

Categories