开发者

How to read a string with spaces in Java

I am trying to read a user input string which must contain spaces. Right now I'm using:

check = in.nextLine();

position = name.names.indexOf(check);
if (position != -1) {
  name.names.get(posi开发者_StackOverflow中文版tion);
} else {
  System.out.println("Name does not exist");
}

this just returns various errors.


your question isn't very clear - specfically you like like you are checking that what the person has typed matches a known list, not that it does or doesn't have spaces in it, but taking you at your word:

  1. Read the whole line in, then check using

a) Regex b) indexof() - if your check is very simple

Possibly also want to do a length check on the input line as well (i.e all lines should be < 255 chars or something) , just to be paranoid

If you are doing more like what you code sample looks like then you do something like

ArrayList<String> KnownListOfNames = ..... 


if(!KnownListOfNames.Contains(UserEnteredString)){
    System.out.println("Name not found");
}

Typically you would also do some basic input validation first - google for "SQL injection" if you want to know more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜