1. 编译时无错误和警告,且运行过程中无异常的代码示例
//编译时无错误和警告,且运行过程中无异常的代码示例
package scanner_test;
import java.util.*;
public class Test {
Scanner s = new Scanner(System.in);
/*Scanner的实例作为类的成员,只生成一次,死循环中调用其方法,结束时应该会
自动调用其close()方法*/
public void test() {
while(true) {
try {
System.out.println("str:"+s.nextLine());
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test t = new Test();
t.test();
}
}
2. 编译时报错的示例代码
//编译时报错
package scanner_test;
import java.util.*;
public class Test2 {
public void test() {
Scanner s = new Scanner(System.in);
while(true) {
try {
System.out.println("str:"+s.nextLine());
}catch(Exception e) {
e.printStackTrace();
}
}
s.close();//编译器提示的 错误:Unreachable code
}
public static void main(String[] args) {
Test2 t = new Test2();
t.test();
}
}
3. 编译时警告的代码示例
//编译时警告
package scanner_test;
import java.util.*;
public class Test3 {
public void test() {
Scanner s = new Scanner(System.in);
//编译器提示的警告:Resource leak: 's' is never closed
while(true) {
try {
System.out.println("str:"+s.nextLine());
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test3 t = new Test3();
t.test();
}
}
4. 编译时无错误和警告,运行过程中出现异常的示例代码
//编译时无错误和警告,运行过程中出现异常
package scanner_test;
import java.util.*;
public class Test4 {
public void test() {
while(true) {
Scanner s = new Scanner(System.in);
try {
System.out.println("str:"+s.nextLine());
}catch(Exception e) {
e.printStackTrace();
}
s.close();
}
}
public static void main(String[] args) {
Test4 t = new Test4();
t.test();
}
}
异常如下:
---------------------