简体   繁体   English

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

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

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

Problems as I see them: 我看到的问题:

  • The code as it stands will only print the first word typed in once the user presses enter 按原样的代码仅会在用户按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);
    }
}

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

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

    }

}

Problem : 问题:

1.you need to send the complete Line and send the String to the function capCase() 1.您需要发送完整的行并将字符串发送到函数capCase()
2.You are not returning the char array back to the caller. 2.您没有将char数组返回给调用方。

Solution
1.use the below statement to read complete Line 1.使用下面的语句阅读完整的行

String str=scanner.nextLine();

2.Change return type of capCase() from void to char[] as below: 2.将capCase()返回类型从void更改为char[] ,如下所示:

public static char[] capCase(String theString)

you should return the char[] variable chars from capCase() function as below: 您应该从capCase()函数返回char[]变量chars,如下所示:

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

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. 但是,如果要获得整个句子,则必须像迭代器一样调用扫描器,然后获取每个下一个标记,然后再调用scan.next()方法。 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());
}`

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

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

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

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

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