Use Scanner in an endless loop keyboard input

1. The sample code and compile-time error warnings, and no abnormality during operation 
// compile-time error and warning, and during operation no abnormal sample code
Package scanner_test;

Import Classes in java.util *;.

Public class {the Test
S = new new Scanner Scanner (the System.in);
/ * examples Scanner as a member of the class is generated only once, call methods infinite loop, should the end of the
automatic call its close () method * /
public void Test () {
the while (to true) {
the try {
System.out.println ( "STR:" + s.nextLine ());
} the catch (Exception E) {
e.printStackTrace ();
}
}
}
public static void main (String [] args) {
the Test new new T = the Test ();
t.test ();
}
}
2. given sample code at compile time 
error // compile time
Package scanner_test;

Import Classes in java.util *;.

public class Test2 {
Test void public () {
Scanner Scanner new new = S (the System.in);
the while (to true) {
the try {
System.out.println ( "STR:" + s.nextLine ());
} the catch (Exception E) {
E .printStackTrace ();
}
}
S.CLOSE (); // compiler hints error: Unreachable code
}
public static void main (String [] args) {
Test2 Test2 new new = T ();
t.test ();
}
}
3. compiled code sample warning
// compile-time warnings
Package scanner_test;

Import Classes in java.util *;.

public class the Test3 {
public void Test () {
Scanner Scanner new new = S (the System.in);
// compiler hints warning: the Resource Leak: 'S' Never iS Closed
the while (to true) {
the try {
System.out.println ( "STR:" + s.nextLine ());
} the catch (Exception E) {
e.printStackTrace ();
}
}
}
public static void main (String [] args) {
the Test3 new new T = the Test3 ();
; t.test ()
}
}
4. compile-time error and warning abnormality occurs during operation of the sample code 
without errors and warnings when compiling //, exception occurred during operation
Package scanner_test;

Import Classes in java.util. *;

public class Test4 {
public void Test () {
the while (to true) {
Scanner Scanner new new = S (the System.in);
the try {
System.out.println ( "STR:" + s.nextLine ());
} the catch (Exception E) {
e.printStackTrace ();
}
S.CLOSE ();
}
}
public static void main (String [] args) {
T = new new Test4 Test4 ();
t.test ();
}
}
abnormality as follows:


--------------------- 

Guess you like

Origin www.cnblogs.com/hyhy904/p/10947642.html