Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output the total number of String Characters

Tags:

java

My Question is what method should I use if I wanted to get the total number of characters a user inputs? without using arrays, i tried using .length() but it did not return all characters say from the first and lastname, it only returned the first name.

Here's an example of my code. (Please dont laugh im really new in programming :) )

System.out.print("Enter your first and last name: ");
String yourName = keyboard.next();
System.out.println("Your name has a total of " + yourName.length() + " numbers");

what happened was if i enter say "Neo Matrix" it would only return 3.

I appreciate any help. thank you!

like image 930
I_Like_Java Avatar asked Apr 13 '12 19:04

I_Like_Java


People also ask

How do you count characters in a string in Java?

String someString = "elephant"; char someChar = 'e'; int count = 0; for (int i = 0; i < someString. length(); i++) { if (someString. charAt(i) == someChar) { count++; } } assertEquals(2, count);

How do you find the number of characters in a string in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .


2 Answers

The method next() only reads the first word of your name. Try nextLine() instead.

like image 121
René Richter Avatar answered Sep 29 '22 09:09

René Richter


You might want to use Scanner.nextLine() to read an entire line.

next() tokenizes the String according to the whitespaces, so you get only the first word - as expected.

like image 37
amit Avatar answered Sep 29 '22 10:09

amit