+ 1

Input multiple numbers in JOptionPane

I have an assignment to create a java program in which the user will enter 12 random numbers using JOptionPane and store them in an array then output the highest and lowest numbers. I tried to use for loop for the JOptionPane but it results only in multiple dialog boxes and only one number can be input in each of them. I'm new to java, and I'm still confused about using JOptionPane. Can you please help me with how can I make it to one dialog box only for all those 12 numbers? This is my code. int num[] = new int[12], x; int highest = num[0], lowest = num [0]; for(x=0; x < num.length; x++) { num[x] = Integer.parseInt(JOptionPane.showInputDialog("Enter 12 random numbers:")); } for(x=0; x < num.length; x++) { if(highest < num[x]) { highest = num[x]; } else if (lowest > num[x]) { lowest = num[x]; } }

17th Nov 2021, 3:09 AM
Purpy 🌟
Purpy 🌟 - avatar
1 Réponse
+ 1
Do this: In one JOptionPane ask user to give inputs separated by spaces like, 0 2 3 18 59...etc. String input = JOptionPane.showInputDialog("Enter inputs separated by spaces"); You store them as string, then: Convert the String to String[] String [] stringArray = input.split(" "); This will create a String array by splitting input string at spaces. Now, convert the String[] array to int[] with for loop. First, create an empty int[] array. int[] intArray = new int[12]; for(int i = 0; i<=stringArray.length-1; i++) { intArray[ i ] = Integer.parseInt( stringArray[ i ] ); } This way you get the int[] array from your JOptionPane in a single go. Later, you can find out the highest and lowest out of them.
17th Nov 2021, 9:19 AM
Bhaveshsingh Pawar
Bhaveshsingh Pawar - avatar