繁体   English   中英

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

[英]Capitalize every word using Scanner(System.in) Java

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

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

我看到的问题:

  • 按原样的代码仅会在用户按Enter键时打印键入的第一个单词
  • 该方法不返回任何内容,因此有效地完成了所有工作并将其丢弃。

所以这是我可能会做的:

为了简洁起见,我将所有内容放到最主要的位置

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

您忘记了调用capCase()方法,您的代码仅要求从stdin输入并直接打印出来

我已经测试过了 有用。

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

    }

}

问题:

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


1.使用下面的语句阅读完整的行

String str=scanner.nextLine();

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

public static char[] capCase(String theString)

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

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

我尝试以主要方法运行程序,但对我来说运行得很好。 但是,如果要获得整个句子,则必须像迭代器一样调用扫描器,然后获取每个下一个标记,然后再调用scan.next()方法。 我的示例实现如下。 您可以在函数中传递每个单词以对其进行处理。

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

我可能会这样做

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

尝试,

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

尝试以下对我有用的代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM