Reputation: 13
I've got a code for a program which is converting (SI) units to an other one. I am working with JOptionPane, and it is working. But I have the problem that I have to input the numbers 8 times and not just 2 times.
Can anyone suggest a solution?
import javax.swing.JOptionPane;
class Aufgabe {
// Newton in Kilopond
static double newton(){
double e = readin()[0];
double newton = e*0.10197;
return newton;
}
// Kilopond in Newton
static double kilopond(){
double f = readin()[1];
double kilopond = f/0.10197;
return kilopond;
}
// method readin
static double[] readin(){
String a = JOptionPane.showInputDialog("newton:");
String b = JOptionPane.showInputDialog("kilopond:");
double n = Double.parseDouble(a);
double k = Double.parseDouble(b);
return new double[]{n, k};
}
// Main-Methode
public static void main (String[] args) {
double a = readin()[0];
double b = readin()[1];
double c = newton();
double d = kilopond();
System.out.println(a + " N = " + c + "kp");
System.out.println(b + " kp = " + d + "N");
}
}
Upvotes: 0
Views: 156
Reputation: 86148
Every time you write readin()
, the method is called, and the user is requested to type the two values. This happens in four places in your code, for a total of 8 dialog boxes.
Instead, call the method just once. Store the return value in a variable and pass the necessary value as an argument to methods that need it:
class Aufgabe {
private static final double CONVERSION_FACTOR = 0.10197;
// Newton in Kilopond
static double newton(double e) {
double newton = e * CONVERSION_FACTOR;
return newton;
}
// Kilopond in Newton
static double kilopond(double f) {
double kilopond = f / CONVERSION_FACTOR;
return kilopond;
}
// method readin
static double[] readin() {
String a = JOptionPane.showInputDialog("newton:");
String b = JOptionPane.showInputDialog("kilopond:");
double n = Double.parseDouble(a);
double k = Double.parseDouble(b);
return new double[] { n, k };
}
// Main-Methode
public static void main(String[] args) {
double[] valuesRead = readin();
double a = valuesRead[0];
double b = valuesRead[1];
double c = newton(a);
double d = kilopond(b);
System.out.println(a + " N = " + c + "kp");
System.out.println(b + " kp = " + d + "N");
}
}
Upvotes: 1