Home > front end >  Having to push Enter 3 times before showing output in Eclipse
Having to push Enter 3 times before showing output in Eclipse

Time:06-05

I wrote a program in Java in Eclipse for user to input SSN and Output reads if valid or not. My program works, it just makes me hit Enter 3 times before showing the output of SSN’s validity. What did I do wrong? At first I was using Scanner System in, but then tried Buffered reader, still having to push Enter 3timesenter image description here

CodePudding user response:

Don't use images for your code. No one can work with that and chances are, the link you provided will be worthless in a week from now. Always enter the pertinent code into your post.

You have to hit enter three times because you are asking for input three times. Every reader.readLine() requires input and or an entry.

You can still use a Scanner object if you want...it might go something like this:

Scanner input = new Scanner(System.in);
String ssn = "";
while (ssn.isEmpty()) {
    System.out.print("Enter SSN in the format of: DDD-DD-DDDD -> ");
    // Get User input and remove any possible whitespaces
    ssn = input.nextLine().replaceAll("\\s ", "");
    // Make what was entered follow the desired format of: DDD-DD-DDDD (where D is a digit)
    if (!ssn.matches("\\d{3}\\-\\d{2}\\-\\d{4}")) {
        System.out.println("Invalid Social Security Number ("   ssn   ")!. Try again...");
        ssn = "";
    }
}
 
System.out.println("You Supplied: "   ssn); 

CodePudding user response:

Was able to fix the code with the answer I received, thanks again! Here is fixed code, tried to upload under comments, but was too long. import java.util.Scanner;

public class SocialSecurityPracticeCh4 {

public static void main(String[] args) {
    //Create a scanner
    Scanner input = new Scanner(System.in);
    
    String ssn;

    
    //Prompt user to enter a social security number 
    System.out.print("Enter a social security number in the format DDD - DD - DDDD: ");
    ssn = input.nextLine();
    char dash = ssn.charAt(0);
    
    boolean isValid = ssn.length() == 11;
    
    if (isValid) 
    System.out.println(ssn   " is a valid social security number.");
    
    else
     System.out.println(ssn   " is an invalid social security number.");
    
    
    
    
    
    
  •  Tags:  
  • java
  • Related