How to parse multiple integers

So, I want to parse several integers, dividing them by ,or a space. Let them say that the user is allowed to enter only 4 numbers max. So, how do I do multiple validation if the user enters, for example, ( 1 2 4 3 )or (1 2 3)? Because it would be impractical to check every choice made. (currently I am checking only 4 options 1, 2 3 or 4), since he cannot make a choice for more than 4

String choose = JOptionPane.showInputDialog(null, ("Some text"));
int userchoice = Integer.parseInt(choose);
if(userchoice ==1){
    //Do something
}
+4
source share
1 answer

If you allow multiple integer inputs separated by spaces, then you can split the input into spaces and parse them one by one, for example:

String input = JOptionPane.showInputDialog(null, ("Some text"));
for (String s : input.split(" ")) {
    int userchoice = Integer.parseInt(s);
    if (userchoice == 1) {    
        // ...
    }
    // ...
}

, :

for (String s : input.trim().split("\\s+")) {
+2

Source: https://habr.com/ru/post/1677106/


All Articles