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;
}
}
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.
I hope this helps