Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...