Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

Java (Length of an input)

So I want to get the length of the input in java, but the (String.length()) doesn't produce a satisfying result. So when I type this code:

String c = "hi hello";
        System.out.print(c.length());

I get 8 which is correct but when I type this code:

Scanner s = new Scanner(System.in);
        String c = s.next();
        System.out.print(c.length());

For "hi hello" is the input, I get 2 not 8. I tried again with different inputs and I found that string.length() have a problem with spaces in inputs. for example, if the input was "123456 78" the output would be 6 not 9. Can you tell me how to get the full length of the input? Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replace s.next() to s.nextLine() and you will get the desired result.

  • next() finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

  • nextLine() returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.


-> "123456 78"
s.next().length() -> "123456".length() -> 6
s.nextLine().length() -> "123456 78".length() -> 9

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...