0

I have the following code that verifies user input using get/set methods.Only strings are acceptable.The while loop should continue to execute till the time the user enters the correct data type.However,my while loop continues to execute despite identifying incorrect data types.Suggestions?

public class SetGet {
    public static void main(String[]args)
    {
        Fraction a=new Fraction();
        Scanner sc=new Scanner(System.in);
        String name;


        boolean type=false;

        while(type==false)
        {
        System.out.println("Enter first name: ");
        name=sc.nextLine();

        a.setfirstName(name,type);
        }

        System.out.println("Name: "+a.getfirstName());
        }

}



public class Fraction {
    private String FirstName;


    public void setfirstName(String firstName,boolean type)
    {

        try
            {
            Integer.parseInt(firstName);
            System.out.println("Invalid "+type);

            }
        catch(Exception e)
        {
            try
            {
                Double.parseDouble(firstName);
                System.out.println("Invalid "+type);
            }
            catch(Exception f)
            {
            type=true;
            this.FirstName=firstName;
            System.out.println("Valid "+type);

            }

        }

    }
    public String getfirstName()
    {
        return FirstName;
    }
}
12dec1990
  • 115
  • 1
  • 9
  • 2
    Side note on quality: **names** are **important**. Just the fact that you call your field `FirstName` ... and then the whole point of your validation is to ensure that the underlying string can be parsed as Double number ... is confusing beyond horizon. Don't do that. Think what your methods, fields are used for. Then name them accordingly. Then: separate concerns. Like: create a method `isDouble(String strValue)` for example; returns true if strValue is a Double ... and then your `setDoubleValueAsString()` will not require any additional validation ... – GhostCat Jun 09 '15 at 15:38

1 Answers1

0

A boolean value is a primitive data type and is thus passed by value only. Only objects are passed by reference. So there are two options for you.

  1. Either make your primitive boolean value a Boolean object (as this will be passed by reference).
  2. Or have the method return a boolean value wether to terminate the loop or not

I hope this helps

Luke Taylor
  • 9,481
  • 13
  • 41
  • 73
  • Not really important here, but the statement "Only objects are passed by reference" is not strictly speaking true. See http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value. – pens-fan-69 Jun 09 '15 at 16:22
  • As the provided link points out, everything is passed by value in Java (including references to objects). A subtle difference to be sure. – pens-fan-69 Jun 10 '15 at 13:38