public static int take1()
{
Scanner in = new Scanner(System.in);
while(true)
{
try
{
System.out.print("\nHow many coloms you want = ");
return in.nextInt();
}
catch(Exception e )
{
System.out.println("Sorry,Please enter only no.");
in.next();
}
}
}
如何关闭扫描程序对象,如果我使用finally关闭此对象或尝试使用资源,它也会关闭System.in,并且我不能多次从流中读取。这样做的最佳方法是什么?
答案 0 :(得分:0)
将finally
阻止并关闭开放资源。
始终执行Java finally块。
try
{
System.out.print("\nHow many coloms you want = ");
return in.nextInt();
} catch(Exception e ){
System.out.println("Sorry,Please enter only no.");
in.next();
}finally{
in.close();
}
编辑AS Na Na Gala
检查是否发生异常然后关闭它让它进入下一个循环util no。进入,否则关闭它。
public static int take1()
{
boolean isExceptionOccured=false;
Scanner in = new Scanner(System.in);
while(true)
{
try
{
System.out.print("\nHow many coloms you want = ");
isExceptionOccured=false;
return in.nextInt();
}
catch(Exception e )
{
isExceptionOccured=true;
System.out.println("Sorry,Please enter only no.");
in.next();
}finally{
if(!isExceptionOccured){
in.close();
System.out.println("resource closed");
}
}
}
}
答案 1 :(得分:0)
你应该用这个:
func signUp(_ email: String, username: String, password: String, data: Data!) {
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
// error here
self.setUserInfo(user, username: username, password: password, data: data)
}else {
print(error!.localizedDescription)
}
})
}
而不是finally {
sc.reset();
}
答案 2 :(得分:-3)
在try中使用变量然后关闭。例如,
public static int take1()
{
Scanner in = new Scanner(System.in);
while(true)
{
try
{
System.out.print("\nHow many coloms you want = ");
int i = in.nextInt();
in.close();
return i;
}
catch(Exception e )
{
System.out.println("Sorry,Please enter only no.");
in.next();
}
}
}
此方法可帮助您关闭对象,避免最终阻止。