I'm new to Java programming and we are currently learning about Strings and Chars. My lab assignment is for the user to enter their SSN and for the program to determine whether it is a valid entry. The format entered needs to be 123-45-6789. So far this is what I have done: package Labs;
import java.util.Scanner;
public class Lab4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a valid SSN");
String ssn = input.nextLine();
System.out.print(ssn);
if (ssn.length() == 11) {
if
}
}
}
I've been looking on the forums here and have found some different answers, but when trying them in my code, something goes wrong. I'm not looking for anyone to write it out for me. What type of methods would I use to check that characters 0-2, 4-5, 7-10 contained a number and characters at 3 and 6 contain a -.
Obviously charAt
and contains
would be helpful, but I'm not sure how to write out the conditions to determine this.
And this question asked How to tell if a SSN is in the right format which appears to be the exact same assignment, I assume we are using the same book doesn't actually give an answer, though its marked as a duplicate, which I can not find the original question. We haven't learned arrays yet either, so I am looking for a more simplistic answer, though I'm sure an example using arrays wouldn't hurt in addition to the simpler answer, so that I can develop my skills more.
Edit Update: Though I'm sure there's a better way to do this, it works.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a valid SSN");
String ssn = input.nextLine();
if (ssn.length() == 11 &&
ssn.charAt(0)>='0' && ssn.charAt(0)<='9' &&
ssn.charAt(1)>='0' && ssn.charAt(1)<='9' &&
ssn.charAt(2)>='0' && ssn.charAt(2)<='9' &&
ssn.charAt(4)>='0' && ssn.charAt(4)<='9' &&
ssn.charAt(5)>='0' && ssn.charAt(5)<='9' &&
ssn.charAt(7)>='0' && ssn.charAt(7)<='9' &&
ssn.charAt(8)>='0' && ssn.charAt(8)<='9' &&
ssn.charAt(9)>='0' && ssn.charAt(9)<='9' &&
ssn.charAt(10)>='0' && ssn.charAt(10)<='9' &&
ssn.charAt(3)=='-' && ssn.charAt(6)=='-')
{
System.out.println(ssn + " is a valid social security number");
}
else
System.out.print(ssn + " is not a valid social security number");
input.close();
}
}