Teknomancer
Teknomancer

Reputation: 23

What can I use to mask a string?

How can I hide parts of a user entry?

Im trying to, as part of a homework assignment, mask the first five digits of a social security number that the user enters. The instructon for the below class says: "The getSsn() method should return a masked version of the social security number that only reveals the last four numbers." This tells me I need to hide the first five. I know the substring and .replace methods could be useful, but Im not sure how to go about it, considering we haven't gone into strings in ultra detail yet. How can I achieve this with what Ive got so far? What do I need to change?

public class Employee extends Person {
    private String SSN;    
    private String x;    
    public Employee(String FirstName, String LastName, String SSN) {

    }    

    public String getSSN(String SSN) {
        String part1 = SSN.substring(0,3);
        String part2 = SSN.substring(4,5);
        String part3 = SSN.substring(6,9);
        SSN = SSN.replace(0,5,'x'); 

        return SSN; 
    }    

    public void setSSN(String SSN) {
        this.SSN = "SSN";
    }
}

As for errors, I know the .replace statement needs to come out.

Upvotes: 0

Views: 1108

Answers (1)

dswdsyd
dswdsyd

Reputation: 616

An approach would be replaceFirst()

String s = "123456789";
s = s.replaceFirst("^.{5}", "*****");

Also, I think your "setSSN" function is incorrect as you have coded it to always to as String "SSN" as opposed to the variable SSN, i.e. should be:

public void setSSN(String SSN) {
this.SSN = SSN;
}

Upvotes: 3

Related Questions