Im working on an assignment for an intro to java class, and having a difficult time, the problem is given as follows:
"Ask the user to input a number. You should use an input dialog box for this input. Be sure to convert the String from the dialog box into a real number. The program needs to keep track of the smallest number the user entered as well as the largest number entered. Ask the user if they want to enter another number. If yes, repeat the process. If no, output the smallest and largest number that the user entered.
This program outputs the largest and smallest number AT THE END of the program when the user wants to quit.
Also, your program should account for the case when the user only enters one number. In that case, the smallest and largest number will be the same."
I am having trouble getting the input dialog boxes to fit into my code and converting that input to integers that I can use for the calculations. Additionally I am not sure of how to account for the user entering more numbers than two, but Im not gonna go into that right now. Any help would be appreciated, thanks in advance!
Here is what I have so far:
package findingminandmax;
import javax.swing.JOptionPane;
public class Findingminandmax
{
public static void main(String[] args)
{
int i = 3;
int j = 2;
int k = max(i, j);
JOptionPane.showMessageDialog(null, "The maximum between " + i +
" and " + j + " is " + k);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
For the input, use:
String s = JOptionPane.showInputDialog(message));
If you want to convert it to a integer:
int i = Integer.parseInt(s);
To a float:
float f = Float.parseFloat(s);
Or to a double:
double d = Double.parseDouble(s);
Also, in order to accept more than 1 input, you could use a for loop or a while:
int n = 5; // Number of times the input will be requested
for (int i = 0; i < n; i++) {
...
// Code here to accept the input
String s = JOptionPane.showInputDialog(message));
...
}
If you are going to store many inputs, you may want to store them in an array. ArrayList