Search code examples
javaoopbooleanencapsulation

Validation within Get/Set Methods Java


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;
    }
}

Solution

  • 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