我有以下代码使用get / set方法验证用户输入。只有字符串是可接受的。while循环应该继续执行,直到用户输入正确的数据类型为止。但是,我的while循环继续执行尽管识别不正确的数据类型。建议?
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;
}
}
答案 0 :(得分:0)
布尔值是基本数据类型,因此仅通过值传递。只有对象通过引用传递。所以有两种选择。
我希望这会有所帮助