Getting data from user in java -
i tried test 2 ways of getting data user. faced 2 errors, attached.
first error:
second error:
have second error (obeject never closed
) every object create scanner class!
import java.io.bufferedreader; import java.io.inputstreamreader; import java.util.scanner; public class inputstreamreaderclass { public static void main(string[] args) { // method 1: inputstreamreader reader = new inputstreamreader(system.in); bufferedreader buffer = new bufferedreader(reader); system.out.println("type text 1: "); string text = buffer.readline(); //method 2: scanner scanner = new scanner (system.in); system.out.println("type text 2: "); string text2 = scanner.nextline(); } }
method 1 have fix. have handle error. issue second method warning, , program still run without fix, idea in habit of closing objects you're not using.
method 1 needs surrounded try/catch
statement, or need throw , exception:
try{ // method 1: inputstreamreader reader = new inputstreamreader(system.in); bufferedreader buffer = new bufferedreader(reader); system.out.println("type text 1: "); string line = buffer.readline(); }catch(exception e){ //handle error }
this because bufferedreader.readline()
throws exception, , need handle it. can more info java documentation
method 2, need close scanner object:
//method 2: scanner scanner = new scanner (system.in); string line2 = scanner.nextline(); system.out.println("type text 2: "); scanner.close();
you don't have close scanner, practice.
Comments
Post a Comment