Capitalize every word using Scanner(System.in) Java

2.1k Views Asked by At

This code should allow the user to input a sentence, change it to lower case, and then capitalize the first letter of each word. But I can't get the scanner to work, it just prints nothing. Any suggestions?

public class Capitalize
{
    public static void capCase(String theString)
    {
        String source = theString;
        StringBuffer res = new StringBuffer();

        char[] chars = theString.toLowerCase().toCharArray();
        boolean found = false;
        for(int i = 0; i<chars.length; i++)
        {
            if(!found&& Character.isLetter(chars[i])){
                chars[i] = Character.toUpperCase(chars[i]);
                found = true;
            } else if (Character.isWhitespace(chars[i])){
                found = true;
            }
        }
    }

    public static void main(String[] args)
    {
        Scanner scanner=new Scanner(System.in);
        System.out.println(scanner.next());
    }
}
8

There are 8 best solutions below

1
On

You forgot to call the capCase() method, your code only asks for input from stdin and prints it out straight

0
On

I've tested it. It works.

import java.util.Scanner;

import org.apache.commons.lang3.text.WordUtils;


public class Capitalize {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        while(s.hasNextLine()) {
            System.out.println(WordUtils.capitalize(s.nextLine()));
        }

    }

}
0
On

Problem :

1.you need to send the complete Line and send the String to the function capCase()
2.You are not returning the char array back to the caller.

Solution
1.use the below statement to read complete Line

String str=scanner.nextLine();

2.Change return type of capCase() from void to char[] as below:

public static char[] capCase(String theString)

you should return the char[] variable chars from capCase() function as below:

return chars;

Complete Code:

public static char[] capCase(String theString)
{

String source = theString;
StringBuffer res = new StringBuffer();

char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
    if(!found&& Character.isLetter(chars[i])){
        chars[i] = Character.toUpperCase(chars[i]);
        found = true;
    } else if (Character.isWhitespace(chars[i])){
        found = true;
    }
}

return chars;
}

public static void main(String[] args)
{
    Scanner scanner=new Scanner(System.in);
    String str=scanner.nextLine();
    
    System.out.println(capCase(str));
}
0
On

I tried running the program in main method it runs fine for me. But if you want to get the whole sentence you will have to call scanner like an iterator and then get each next token bu calling scanner.next() method Scanner deliminates words in a sentence on the basis of white spaces. my example implementation is as follows. The you can pass each word in the your function to process it.

`public static void main(String[] args) {
    Scanner scanner=new Scanner(System.in);
    while (scanner.hasNext())
        System.out.println(scanner.next());
}`
0
On

I would probably do this

public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  while (scanner.hasNextLine()) { // While there is input.
    String line = scanner.nextLine(); // read a line.
    int i = 0;
    for (String s : line.split(" ")) { // split on space... word(s).
      if (i != 0) {
        System.out.print(" "); // add a space, except for the first word on a line.
      }
      System.out.print(capCase(s)); // capCase the word.
      i++; // increment our word count.
    }
    System.out.println(); // add a line.
    System.out.flush(); // flush!
  }
}

public static String capCase(String theString) {
  if (theString == null) {
    return ""; // Better safe.
  }
  StringBuilder sb = new StringBuilder(theString
      .trim().toLowerCase()); // lowercase the string.
  if (sb.length() > 0) {
    char c = sb.charAt(0);
    sb.setCharAt(0, Character.toUpperCase(c)); // uppercase the first character.
  }
  return sb.toString(); // return the word.
}
0
On

Problems as I see them:

  • The code as it stands will only print the first word typed in once the user presses enter
  • The method doesn't return anything, so effectively it does all that work and discards it.

So here is what I might do:

I'm going to put everything in main for the sake of concision

public class Capitalize {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String sentence = Scanner.nextLine();
        StringBuilder ans = new StringBuilder(); // result
        for(String s : sentence.split(" ")) { // splits the string at spaces and iterates through the words.
            char[] str = s.toLowerCase().toCharArray(); // same as in OPs code
            if(str.Length>0) // can happen if there are two spaces in a row I believe
                str[0]=Character.toUpperCase(str[0]); // make the first character uppercase
            ans.Append(str); // add modified word to the result buffer
            ans.Append(' '); // add a space
        }
        System.out.println(ans);
    }
}
0
On

Try,

public static void main(String[] args) {
    System.out.println(capCase("hello world"));
}

public static String capCase(String theString) {

    StringBuilder res = new StringBuilder();

    String[] words=theString.split(" +");
    for (String word : words) {
        char ch=Character.toUpperCase(word.charAt(0));
        word=ch+word.substring(1);
        res.append(word).append(" ");
    }

    return res.toString();
}
0
On

Try this code it worked for me:

import java.util.Scanner;

public class Capitalize {
  /**
   * This code should allow the user to input a sentence, change it to lower
   * case, and then capitalize the first letter of each word. But I can't get
   * the scanner to work, it just prints nothing. Any suggestions?
   * 
   * @param theString
   */
  public static void capCase(String theString) {

    String source = theString.trim();
    StringBuffer res = new StringBuffer();
    String lower = theString.toLowerCase();
    String[] split = lower.split(" ");
    for (int i = 0; i < split.length; i++) {
      String temp = split[i].trim();

      if (temp.matches("^[a-zA-Z]+")) {
        split[i] = temp.substring(0, 1).toUpperCase()
            + temp.substring(1);
      }
      res.append(split[i] + " ");
    }
    System.out.println(res.toString());

  }

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    capCase(scanner.nextLine());
    // System.out.println(scanner.next());
  }
}