Gned Gned - 3 months ago 49
Java Question

Java - While loop (with try/catch/finally) only iterates once, even when condition is met

In the following code, my while loop is not working. It iterates once, but never again, even when the condition is met. I tried changing the flag to "N", and it failed to iterate the first time, so I know the issue is not in the actual while condition declaration. I also made sure that I was saving the "Y" or "N" as Strings, not as chars. I tried adding a continue statement in both the finally clause and the catch clause. Still no go. What the heck am I missing?

/** This program asks for a person's name and SSN, validates
the SSN and throws an exception if it is invalid.*/

import java.util.Scanner;

public class SocSecProcessor
{
/**
main User enters SSN, method uses isValid() to validate and throws exception
if isValid() returns false. Prints entered data and displays message about validity.
@exception SocSecException
*/
public static void main(String[] args) throws SocSecException
{
Scanner keyboard = new Scanner(System.in);
String name;
String SocSecNum;
String tryAgain = "Y";

System.out.print("Name?");
name = keyboard.next();
keyboard.nextLine();

System.out.print("SSN?");
SocSecNum = keyboard.next();
keyboard.nextLine();


while(tryAgain == "Y")
{
try
{
isValid(SocSecNum);
System.out.println(name + " " + SocSecNum + " is valid.");
}
catch (SocSecException e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.print("Continue?");
tryAgain = keyboard.next().toUpperCase();
//System.out.println(tryAgain);
}
}
}

/**
isValid Checks validity of SSN
@return true if SSN is valid, false if SSN is invalid
@exception SocSecException
*/
public static boolean isValid(String ssn) throws SocSecException
{
boolean value;
for (int i = 0;i < ssn.length() ; i++)
{
String digit = ssn.substring(i, i + 1);
if (!digit.matches("[0-9]") && !digit.matches("-") )
{
value = false;
throw new SocSecException("contains character that"
+ " is not a digit.");
}
}
if (ssn.length() != 11)
{
value = false;
throw new SocSecException("wrong number of characters.");
}
else if (ssn.substring(3, 4) != "-"
|| ssn.substring(6, 7) != "-")
{
value = false;
throw new SocSecException("dashes at wrong position.");
}

else
value = true;

return value;
}
}


And the custom exception class:

/**
This is a custom Exception class that handles an exception that
may be thrown when an invalid SSN is entered.
*/


public class SocSecException extends Exception
{
/**
This constructor specifies the exact formatting error that caused the exception.
@param error A description of what caused the exception.
*/
public SocSecException(String error)
{
super("Invalid Social Security Number, " + error);
}
}

Answer

This doesn't work: tryAgain == "Y".

Try changing your condition to: while (tryAgain.equals("Y")).