accept only a single digit in java

后端 未结 3 1314
感动是毒
感动是毒 2021-01-14 15:02

I am writing a simple program that takes multiple inputs and displays the largest then second largest. My only problem is that I want the program to accept only single digi

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-14 15:44

    //Set the counter
    counter++;
    while (true) {
        //Input integer, set the largest number as the first output
        number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
        if (number < 10 && number > -10) break; //If it's one digit, it's OK
        JOptionPane.showMessageDialog(null, "Enter only one digit",
            "Too many digits", JOptionPane.ERROR_MESSAGE);
    }
    

    What this does is start an infinite loop. If the number is only one digit, it will end the loop and continue on. Otherwise, it will start from the beginning of the loop again and ask for a valid number.

提交回复
热议问题