一、函数中的Scanner
1.在主函数中多次调用含有输出并已经被关闭的函数
1).代码
import java.util.Scanner;
public class Login{
public static void main(String[] args) {
int i = 0;
for( ; i < 3; i++) {
keyEnter();
}
}
public static void keyEnter() {
Scanner sc = new Scanner(System.in);
int i = 2;
for ( ; i >= 0; i--) {
System.out.print("Please enter your password > ");
String password = sc.nextLine();
if (password.equals("123password")) {
System.out.println("Success!");
break;
} else {
if (i == 2) {
System.out.println("Fail, you only have " + i + " chances left.");
} else if(i == 1){
System.out.println("Fail, you only have one more chance.");
} else {
System.out.println("You have no chance left.");
}
}
}
sc.close();
}
}
2).运行错误
编译时并不会出现问题,但在运行时无法进行第二次输入。
这样说明在函数中可以进行输入并且也可以在函数中进行Scanner sc = new Scanner(System.in);,及定义Scanner对象 。
import java.util.Scanner;
public class LoginAgain{
public static void main(String[] args) {
keyEnter();
}
public static void keyEnter() {
Scanner sc = new Scanner(System.in);
int i = 2;
for ( ; i >= 0; i--) {
System.out.print("Please enter your password > ");
String password = sc.nextLine();
if (password.equals("123password")) {
System.out.println("Success!");
break;
} else {
if (i == 2) {
System.out.println("Fail, you only have " + i + " chances left.");
} else if(i == 1){
System.out.println("Fail, you only have one more chance.");
} else {
System.out.println("You have no chance left.");
}
}
}
sc.close();
}
}
就像这样的代码是可以进行运行的。
二、定义多个Scanner对象
下面链接中的文章讲述了定义多个Scanner(System.in)对象是毫无意义的,只要一次关闭标准输入流,就会导致其它即使是在.close()函数下方定义的Scanner(System.in)对象无法正常运行,尽管编译器不会察觉到这样的问题。
请看我在CSDN上找到的别的作者写的代码例子。
https://blog.csdn.net/jhljhl12138/article/details/80764590
三、应用.close()函数的好处
应用.close函数可以将Scanner使用的io流关闭,而且io流非常占內存。