Scanner -- how to count spaces a part of a string

I'm fooling around with Scanner in a little program just to teach myself. Right now, when given the chance to enter data, anything after a space is ignored, so, for example, if one enters "John Smith" for a name entry, on printout it only says "John." How can I fix this?

Melanie_Green wrote:
Opps forgot to close the scannerUmmm... As a general rule of thumb... If you open it, close it... and conversely: If you didn't open it, don't close it... any other way lies madness, like having to check if the stream has been closed by something else before every write. Yeck!
System.in, out, and err are opened and closed for you automatically... so you shouldn't (IMHO) close a scanner on System.in, because it would close the underlying System.in stream... which probably isn't what you wanted to do anyway.
And (just my humble opinion) I'd regard that "input loop" as "an abuse of loops"... because it's more complicated than it needs to be. However...
If one where to delegate the "simple attributes" of a "bean-like" class to a Map... Hmmm... the below code concept still isn't (IMHO) actually useful for real apps, because it's limited to String attributes only, but it was an interesting learning exercise none-the-less... and one could conceivably extend it to support all the primitive types, but what's the point... then you may as well just write simple old beans, forget about all the "clever stuff" under the hood, and get on with what the real problems ;-)
package forums;
import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;
* A base class for simple Data Transfer Objects with only String attributes.
abstract class DTO
  private static final Scanner SCANNER = new Scanner(System.in);
  protected final String CLASS_NAME;
  private final String[] ATTRIBUTE_NAMES;
  private final String PROMPT_FORMAT;
  private Map<String, String> attributes = new HashMap<String, String>();
  public DTO(String[] attributeNames) {
    this.CLASS_NAME = getClassNameOnly(this.getClass());
    this.ATTRIBUTE_NAMES = attributeNames;
    this.PROMPT_FORMAT = "    %-"+maxLengthOf(attributeNames)+"s : ";
  public void enterAttributes() {
    System.out.println("Please enter the attributes for "+CLASS_NAME+" : ");
    for (String attributeName : ATTRIBUTE_NAMES) {
      String prompt = String.format(PROMPT_FORMAT,attributeName);
      String attributeValue = read(prompt);
      attributes.put(attributeName, attributeValue);
  @Override
  public String toString() {
    StringBuilder result = new StringBuilder();
    result.append("<").append(CLASS_NAME).append(">\n");
    for (Map.Entry<String,String> attr : attributes.entrySet()) {
      result.append("<").append(attr.getKey()).append(">");
      result.append(attr.getValue());
      result.append("</").append(attr.getKey()).append(">\n");
    result.append("</").append(CLASS_NAME).append(">\n");
    return result.toString();
  // ========== HELPER METHODS ==========
  // NOTE: in a real system these would be in various Utilz classes.
  // read from krc.utilz.io.Conzole
  private static String read(String prompt) {
    System.out.print(prompt);
    return SCANNER.nextLine().trim();
  // read from krc.utilz.Clazz
  private static String getClassNameOnly(Class clazz) {
    String fullName = clazz.getName();
    return fullName.substring(fullName.lastIndexOf('.')+1);
  // read from krc.utilz.Stringz
  private static int maxLengthOf(String[] names) {
    int max = names[0].length();
    for(int i=1; i<names.length; i++) {
      max = Math.max(max, names.length());
return max;
* A Person object
class Person extends DTO
private static final String[] ATTRIBUTE_NAMES = {
"FirstName", "LastName", "Street", "State"
public Person() {
super(ATTRIBUTE_NAMES);
public class PersonDatabase3
public static void main (String[] args) {
try {
Person person = new Person();
person.enterAttributes();
System.out.println(person);
} catch (Exception e) {
e.printStackTrace();
Cheers all. Keith.
Edited by: corlettk on 21/06/2009 16:47 ~~ Clearer.

Similar Messages

  • How to count no. of tokens in a string?

    hello everybody?
    I am using StringToknizer to read a csv file line by line.
    My problem is:
    i want to know how many tokens are there in a particular row. How to count it at a streatch?
    i am using
    <%
    if (st.hasMoreTokens())
         a3=st.nextToken().trim();
    %>i thought of using String.split(), but, i don't know how to use it?(what class to import)
    Anyguidence will be appreciated
    Thanks for your time.
    Regards,
    Ashvini

    StringTokenizer will do it for you!
    int numberOfTokens = st.countTokens();m

  • How do count the character in the given string?

    hi all,
    i have astring like 'AAAARAMARAOAAA'.
    i want count how many 'A's in this string using sql statement.

    Is that a joke? You asked that in a previous thread of yours: how do count how many 'A' s in this string using sql stmt?.
    C.

  • How Do I Mirror A Part Of A String?

    Dear Programmers,
    Does Anyone know how to mirror a string in C#:
    For example:  looks -> skool
    Thank you in advance,

    There is a Reverse method:
    string s = "looks";
    s = new string(s.Reverse().ToArray());
    Best way to reverse a string:
    http://stackoverflow.com/questions/228038/best-way-to-reverse-a-string
    And you can get a part of a string using the Substring method:
    https://msdn.microsoft.com/en-us/library/system.string.substring(v=vs.110).aspx
    Please remember to mark helpful posts as answer to close your threads and then start a new thread if you have a new question.

  • How to count number of words in a string?

    Is it only possible by counting the number of white spaces appearing in the string?

    Of course that also depends upon how accurate you need to be and what the string contains. It is completely possible that there might be a line break which doesn't have a trailing or leading space.
    Like that.
    In that case Flash's representation of the string is likely "...space.\n\nLike that.." In chich case "space.\n\nLike" will be a word.
    Also if you split on space and there are places where there are two spaces in a row you could inflate your number. So somthing that changes newlines (and returns) to spaces, then removes any multiple spaces in a row, and finally does the split/count thing would be more accurate.
    But it all depends upon what you need.

  • How Can I extract each part of a string ??

    Dear Sir:
    I have a string like following to connect to Oracle Database:
    JDBC_URL= jdbc:oracle:thin:@localhost:1521:ABChere,
    I have Variables like:
    driverClass="";
    Hostname = "";
    port = "";
    SID="";
    etc
    I try to extract each part from this JDBC_URL,
    then assign them to following variable separately:
    driverClass="jdbc:oracle:thin";
    Hostname = "localhost";
    port = "1521";
    SID="ABC";
    Can some guru help give some good example and show how to do it??
    Thanks and have a nice weekends.

    try using a regular expression (regex).
    here, i am going to try to freeball it:
    // JDBC_URL= jdbc:oracle:thin:@localhost:1521:ABC
    Pattern p = Pattern.compile("(JDBC_URL)(\\s*)(=)(\\s*)(.*?:.*?:.*?)(:)(@)(.*?)(:)(.*?)(:)(.*?)")
    Matcher m = p.matcher(text)
    if(m.matches()) or if(m.lookingAt()){
    String driverclass = m.group(5);
    String hostname = m.group(8);
    ...group(10);
    ...group(12);
    }note that (\\s*) means "any amount of whitespace" and (.*?) means "any amount of any character (reluctantly)".
    i used that because i dont know the constraints on those values. for only numbers you can use (\\d+) etc
    [http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html|http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html]
    also, i put everything into ( ) - which is called a capture group - but that was just to make it clearer. in your final regex you may get
    rid of most of those.

  • How to count number of characters in a string?

    Hi
    I need to display values in a script. but the alignment getting distrubed if it is less than 20 charaters, for exmple material descirption is only displaying 20 characters in script. if it is less than 20 charcters the alignment getting changed.
    please help me ...urgent..
    thanks in advance...

    solution to this problem in script is not to count the characters but to align them based on positions .
    1.
    Use the tab positions  for that paragraph format to display the values in a finite format .
    In this u need to give the position start and position end length and use the same in the script as
    p ,,&itab-f1&
    say my value has to print from position 125mm to 155 mm
    i take one tab position for this paragraph format P and maintain the same in the output.
    here ,, is the tab position .
    See whether it is one character or 20 character it has to behave the same way it should not be misaligned .
    check the tab position for that paragraph format in Tabs ..
    regards,
    vijay.

  • How to count the number of times a string occurs in a column.

    I am listing team names in a column and want to have a tally at the bottom. In Excel I can use =SUM(IF(range="text",1,0)), but Numbers will not accept a range in that IF statement. ANy suggestions on a formula for his? I know I could create hidden columns and put formulas in all those and hen count them, but that sure seems like a heard way to resolve what should be one formula.
    THanks!

    Those which took time to read carefully *_iWork Formulas and Functions User Guide_* are aware of the availability of wildcard characters.
    =COUNTIFI(range;"=text")
    will do the trick.
    Yvan KOENIG (VALLAURIS, France) lundi 26 avril 2010 17:36:34

  • How can I take a part of a String

    Example:
    10:20:30
    how can I take the 20, the 4th and 5th character of the String??
    Cheeres

    u can use the substring function for this........
    String name = "10:20:30";
    name = name.substring(4,5);
    this will give u the exact those 2 digits.........
    for any query see java.lang.String methods
    regards
    Ankur Aggarwal

  • How to count number of vowels in the String?

    Write a program that calculates the total number of vowels contained in the String" Event Handlers is dedicated to making your event a most memorable one."
    Please help!

    http://leepoint.net/notes/javanotes/40other/20examples/60Strings/example_countVowels.html

  • How to allocate space for headers in reports through line size r line count

    hi ,
    may i know how to allocate space for a header ( we do the same for footer through line-count ( footer space ) ) through line size or line count in reports...
    thanks in advance..

    Hi..,
    There is no need to reserve any space for the header. TOP-OF-PAGE can by default allocates the space for the header.
    If you still having confusion just  go ahead with this link. This is the research on same thing in defferent way.
    [Link|lines reservation for TOP-OF-PAGE & END-OF-PAGE;
    Thanks,
    Naveen.I

  • How to count number of autoextents that had took place between a period.

    urgent question
    Hi all
    how to provide me a report for getting the result of the Disk Drive Space usage (drive letter) that shows how quickly the space is being used up by the database(dbf files).
    Or how to count the number of autoextents that had took place between a certain period of time.
    either by cmd promt or OEM would be fine
    Oracle database 10g(single instance)
    OS:Windows 2003 server
    thanks
    Anto

    hi justin and Pavan
    First Thanks for your immediate responce,
    Secoundly client has asked for the growth report at the OS level and not at the database level. but the growth is with respect to the autoextent feature that oracle has over the datafiles.
    I was thinking that i could get a view or some history log to get this data retrieved from the past may be of a months data.I normally manually check the data base growth with the following script
    SELECT total_space,free_space,
    (NVL(total_space,2)-NVL(free_space,2) ) used_space
    FROM (select round(SUM(Bytes/1024/1024/1024),2) Total_space
    from DBA_data_files
    (select round(SUM(Bytes/1024/1024/1024),2) free_space
    from DBA_free_space
    but this is Oracle DB level.
    Any ideas for the report.like a query or somewhere in OEM
    Thanks
    Anto

  • How to count the number of rows in a resultser object?

    hi there
    how to count the number of rows in a resultser object which may contains millions of rows? besides using a while loop? thanks

    You don't, you execute a query whose result is the record count of those records that match the search and then you execute the actual query to create your record set. Typically you do
    select count(id) from YourTable where [filter]
    from the resulting ResultSet do
    int res.getInt(1);
    which gives you the count and then
    select id from YourTable where [filter]
    to produce the actual result set.
    in the second query the id part can be substituted with the actual fields you want.

  • How to count words in a text ?

    Hi all,
    can anyone show me how to count the number of words in a text.
    thank in advandce,
    Toan.

    Hi,
    Are you reading the text from a file or is it stored in a string buffer?
    The best way would be to use a StringTokenizer assuming that all your words are separated by a space ' ' you could use that as your delimiter.
    Something like..
    String text = "This is just a bunch of text stored as a string.";
    StringTokenizer words = new StringTokenizer( text, " ", false );
    int numberOfWords = words.countTokens();I hope that helps,
    .kim

  • How to remove space below the table in smartforms

    how to remove space below the table in smartforms

    maintain a loop counter for item say count
    and in text editer write
    if count > 6
      new-page.
    endif.

Maybe you are looking for