使用Scanner(System.in)Java将每个单词大写

时间:2013-12-07 06:16:50

标签: java java.util.scanner system.in

此代码应允许用户输入句子,将其更改为小写,然后将每个单词的第一个字母大写。但我不能让扫描仪工作,它只是打印什么。有什么建议吗?

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 个答案:

答案 0 :(得分:1)

我看到的问题:

  • 目前的代码只会在用户按下
  • 后打印输入的第一个单词
  • 该方法不返回任何内容,因此它可以有效地完成所有工作并将其丢弃。

所以我可能会这样做:

为了简洁,我将把所有东西放在主要的

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);
    }
}

答案 1 :(得分:0)

你忘了调用capCase()方法,你的代码只询问stdin的输入并直接输出

答案 2 :(得分:0)

我已经测试过了。有用。

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()));
        }

    }

}

答案 3 :(得分:0)

问题:

1.您需要发送完整的Line并将字符串发送到函数capCase()
2.您没有将char数组返回给调用者。

<强>解决方案
1.使用以下声明阅读完整的行

String str=scanner.nextLine();

2.将capCase()的返回类型从void更改为char[],如下所示:

public static char[] capCase(String theString)

您应该从char[]函数返回capCase()变量字符,如下所示:

return chars;

完整代码:

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));
}

答案 4 :(得分:0)

我尝试在main方法中运行程序,它运行正常。但是,如果你想获得整个句子,你将不得不像迭代器一样调用扫描器然后获取每个下一个令牌bu调用scanner.next()方法Scanner根据空格来消除句子中的单词。我的示例实现如下。您可以传递函数中的每个单词来处理它。

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

答案 5 :(得分:0)

我可能会这样做

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.
}

答案 6 :(得分:0)

尝试,

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();
}

答案 7 :(得分:0)

试试这个适合我的代码:

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());
  }
}