• Post Reply Bookmark Topic Watch Topic
  • New Topic

how can i store multiple lines into one variable?  RSS feed

 
Dan Rana
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how would i store multiple strings into one variable?
the scanner would read the user's input until the person enter's a blank string
for ex:
"Please enter text"
hi
hey
hello
<enter>

how can i store "hi, hey, and hello" into one string and stop scanning when they enter a blank string?
can i do this using "\n" ?
 
Marcus Kelvin
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can i store "hi, hey, and hello" into one string


Strings are immutable so you can't add anything to them. However, you can concatenate three existing strings into one new one. Or: you could use a StringBuffer or StringBuilder.

and stop scanning when they enter a blank string?


If you are reading each line into a string, you could use a regular expression match:



String.matches() refers to the whole string, not just a part. The regex specifier \s includes spaces, tabs ('\t'), newlines ('\t') and carriage returns ('\r'), so if that matches, there is nothing else in the string and you can consider it empty. If you don't know about regular expressions specifiers: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want access to each individual String later in your program then you might want to add them to a List rather than concatenating them all into one String.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!