简体   繁体   中英

Reading from text area by line and assigning variables

I need to append variables to each line of text from a TextArea . The TextArea is coded, and works perfectly. I can retrieve information from the TextArea by using TextArea.getText(); To break it apart, I am trying to use a BufferedReader . Unfortunately, this does not work. Is there a different way of doing this? Here is an example of how the information needs to be written in the text area:

"workerName"

"workerDepartment"

"workerNumber"

BufferedReader inStream= new BufferedReader 
(new InputStreamReader(TextArea.getText()));

String workerName = "";

String workerDepartment = "";

int workerNumber = 0;

String line = inStream.readLine();            

while (line != null) {                        

 workerName = line;

 line = inStream.readLine();               

 workerDepartment = line;

 line = inStream.readLine();               

 workerNumber = Integer.parseInt(line);

 }

 inStream.close();                  

if the lines are separated by any delimiter(for example newline, comma...) , then use split method of String and put the delimiter

String[] lines = TextArea.getText().split("\n");

//then you can access your array
String workerName = lines[0];
String workerDepartment = lines[1];
// and so on

Also you need to check array size before getting the value to prevent ArrayOutOfIndexException, for example if there are two lines only then you should not call lines[2], so do the check:

   if ( lines.length < 3 ) {
      // input is not complete, show error message
   }
   else {
      // do your splitting and reading values
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM