Home > Software design >  How to validate or restrict user from inputting alphabet or numbers
How to validate or restrict user from inputting alphabet or numbers

Time:12-16

I've been trying to figure the problem in my code for hours is there any way to solve this? If so please help me fix this problem. It runs but the code inside while doesn't work the way it is intended to even though the condition make sense or I just don't know how while works??? Anyways, thank you for the people that will help. That's all the details

import java.text.DecimalFormat;
import javax.swing.JOptionPane;
//imported JoptionPane for a basic UI
//Don't mind the comments

public class Calculator {
    public static void main(String[] args) {
     
    DecimalFormat format = new DecimalFormat("0.#####"); 
    //Used this class to trim the zeroes in whole numbers and in the numbers with a trailing zero
        
        String[] response = {"CANCEL", "Addition", "Subtraction", "Multiplication", "Division", "Modulo"}; 
        //Used array to assign reponses in the response variable(will be used in the showOptionDialog())
        //CANCEL is 0, Addition is 1, Subtraction is 2 and so on. Will be used later in switch statement

        int selectCalculation = JOptionPane.showOptionDialog(null,
                                     "SELECT CALCULATION THAT YOU WANT TO PERFORM:", 
                                     "SELECT CALCULATION", 
                                     JOptionPane.YES_NO_OPTION, 
                                     JOptionPane.QUESTION_MESSAGE, 
                                     null, 
                                     response, 
                                     null);

        String numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
        //Used the class String instead of the data type double because I will be using a String method in while condition
            while (numberInput1.matches("[a-zA-Z]"))
            //Used regex here basically saying if numberInput1 does contain letter then start the loop until user inputs number
            {
                JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
                //Shows warning message so user will know what the accepted input is
                    numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
            }

        String numberInput2 = JOptionPane.showInputDialog(null, "ENTER THE SECOND NUMBER:");
        //Same reason as stated previously
            while (numberInput2.matches("[a-zA-Z]")) {
                JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
                    numberInput2 = JOptionPane.showInputDialog(null, "ENTER THE SECOND NUMBER:");
            }

        double firstNumber = Double.parseDouble(numberInput1);
        double secondNumber = Double.parseDouble(numberInput2);
        //Converts the numberInputs to double so Java will add numbers instead of String later

        switch (selectCalculation)
        //Used switches instead of if else because it will be a longer process if I used if else
        {
            case 1:
                double sum = firstNumber   secondNumber;
                JOptionPane.showMessageDialog(null, format.format(firstNumber)   " and "   format.format(secondNumber)   " is equals to "   format.format(sum), "The sum of:", JOptionPane.INFORMATION_MESSAGE);
                break;
            case 2:
                double difference = firstNumber - secondNumber;
                JOptionPane.showMessageDialog(null, format.format(firstNumber)   " and "   format.format(secondNumber)   " is equals to "   format.format(difference), "The difference of:", JOptionPane.INFORMATION_MESSAGE);
                break;
            case 3:
                double product = firstNumber * secondNumber;
                JOptionPane.showMessageDialog(null, format.format(firstNumber)   " and "   format.format(secondNumber)   " is equals to "   format.format(product), "The product of:", JOptionPane.INFORMATION_MESSAGE);
                break;
            case 4:
                double quotient = firstNumber / secondNumber;
                JOptionPane.showMessageDialog(null, format.format(firstNumber)   " and "   format.format(secondNumber)   " is equals to "   format.format(quotient), "The quotient of:", JOptionPane.INFORMATION_MESSAGE);
                break;
            case 5:
                double remainder = firstNumber % secondNumber;
                JOptionPane.showMessageDialog(null, format.format(firstNumber)   " and "   format.format(secondNumber)   " is equals to "   format.format(remainder), "The remainder of:", JOptionPane.INFORMATION_MESSAGE);
                break;    
            default:
                JOptionPane.showMessageDialog(null, "MADE BY: GABRIEL POTAZO", "CALCULATION CANCELLED",JOptionPane.ERROR_MESSAGE);
                break;
        }
    }
}

CodePudding user response:

Hi your question was unclear in many places, but I believe you just need to validate the input value to have only numbers/alphabets/alpha-numeric.

  String numberInput1 = JOptionPane.showInputDialog(null, "ENTER THE FIRST NUMBER:");
    //If its not Numbers matching
    if (!Pattern.matches("[0-9]*", numberInput1)){
       JOptionPane.showMessageDialog(null, "Make sure to enter numbers ONLY", "INVALID", JOptionPane.WARNING_MESSAGE);
       //Clear your Input Box
    }

For Matching Only Alphabets

Pattern.matches("[a-zA-Z]*", numberInput1)

For matching alphanumeric

Pattern.matches("[a-zA-Z0-9]*", numberInput1)

I'm not convinced validating with Loops, but I recommend checking out the Swing tutorial on Dialogs, and how to use JOptionPane easily so you don't need to validate the input.

CodePudding user response:

if you want that user can input expect Alphabet or Numbers then user only can input special characters as a input

for this just simple

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".kotlin.DemoActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="50sp"
        android:hint="Type something..."
        android:inputType="text"
        android:digits="!@#$%^*()-_/*- =[]{};:'?.,></"  //here you can edit 

        />

</RelativeLayout>


class DemoActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_demo)
    }
}
  • Related