0

So currently I have a setup where users enter a number from scanner util and I have a boolean that checks if the string entered is 4 digits and is only digits how can I create a boolean that would check it compared to another string for instance:

String pin = "6357";

what type of boolean would I have to compare the string to the one entered by user. Here is my current code checking the length go the string:

import java.security.MessageDigest;
import java.util.Scanner;

public class pin
{

public static void main( String[] args ) {
    Scanner kbd = new Scanner( System.in );
    String      pin;
    System.out.print( "Enter pin: " );
    pin = kbd.next();
    System.out.println( "Valid: " + isValid(pin) );
    System.out.println( "Is int: " + isInt(pin) );
    System.out.println( "MD5: " + md5HexString(pin) );
}

public static boolean isInt( String s ) {
    try {
        int i = Integer.parseInt( s );
        System.out.println( "Int: " + i );
        return true;
    }
    catch( Exception ex ) {
        return false;
    }
}

public static boolean isValid( String s ) {
    return s.matches( "\\d{4}" ); // must be 4 digits long
}

As can be seen this does not compare it to another existing string so what if I had something like this:

import java.security.MessageDigest;
import java.util.Scanner;

public class pin
{
   String pinnum = "6357";

public static void main( String[] args ) {
    Scanner kbd = new Scanner( System.in );
    String      pin;
    System.out.print( "Enter pin: " );
    pin = kbd.next();
    System.out.println( "Valid: " + isValid(pin) );
    System.out.println( "Is int: " + isInt(pin) );
    System.out.println( "MD5: " + md5HexString(pin) );
}

public static boolean isInt( String s ) {
    try {
        int i = Integer.parseInt( s );
        System.out.println( "Int: " + i );
        return true;
    }
    catch( Exception ex ) {
        return false;
    }
}

public static boolean isValid( String s ) {
    //what to put here?
}

In this example I pre set up a pin that I would like to check if what the user entered through scanner util matches exactly. Is this possible?

2 Answers2

1

you could use the .equals() method to comapare two values to see if they match.

pinnum.equals(s)

a more detailed explanation can be found here: How do I compare strings in Java?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Connor J
  • 540
  • 1
  • 6
  • 17
  • i just left it there to show that its the user entered pin and not the hardcoded pin - but yeah you are right - shouldn't use those characters! – Connor J Apr 21 '18 at 18:17
  • Thanks for the code and thanks for whoever left the link too will check that out for more since I will be expanding more later! –  Apr 21 '18 at 18:18
1

If you are really working on validations, for the sake of Single Responsibility (SOLID Principles) it is better to have this kinds of validation things in another class. In this case you can use .equals() method.

raydex
  • 19
  • 1
  • 3