具有特定要求的Sentence Capitalizer

时间:2017-10-06 00:29:14

标签: java arrays stringbuilder

这很难解释,但我正在尝试创建一个程序,只能将每个以句号,问号或感叹号结尾的单词的字母大写。我输入任何标记时都设法收到结果,但仅在第二次输入时才收到。换句话说,我必须按两次输入以获得结果,我不知道为什么。我仍在自己的工作,但我坚持这个问题。

import java.util.*;

public class SentenceCapitalizer
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Input a sentence: ");
        String line = keyboard.nextLine();

        String wrong = keyboard.nextLine();
        String[] check = {".!?"};
        String upper_case_line="";
        Scanner lineScan = new Scanner(line);

        for (String sent : check)
        {
            if (sent.startsWith(wrong))
            {
                System.out.println("cant use .?!");
            }
            else
            {


             /* if (line.startsWith(" "))//if starts with space
                System.out.println("good");
            else
                System.out.println("bad");
            */

            //if (int i = 0; i < line.length; i++)
            //{char c = line.chartAt(i);
                while(lineScan.hasNext())
                {
                    String word = lineScan.next();
                    upper_case_line +=   Character.toUpperCase(word.charAt(0)) +
                            word.substring(1) + " ";
                }

                System.out.println(upper_case_line.trim());
            }
        } 

    }
}

1 个答案:

答案 0 :(得分:0)

<强>解决方案

嘿,只是你问题的快速解决方案。将字符串转换为字符数组,然后检查字符数组'。!?'如果它找到了值,那么它将使下一个字母为大写!

public class SentenceCapitalizer {

public static void main(String[] args) {
    //Scanner, Variable to hold ouput
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Input a sentence: ");
    String line = keyboard.nextLine();

    //Char array, boolean to check for capital
    char [] lineChars = line.toCharArray();
    boolean needCapital = false;

    //String to hold output
    String output = "";

    //Check for period in line
    for (int i = 0; i < lineChars.length; i++) {

        //Make sure first char is upper case
        if (i == 0) {
            lineChars[i] = Character.toUpperCase(lineChars[i]);
        }

        //Check for uppercase if char is not space
        if (needCapital && Character.isLetter(lineChars[i])) {
            lineChars[i] = Character.toUpperCase(lineChars[i]);
            needCapital = false;
        }

        if (lineChars[i] == '.' || lineChars[i] == '?' || lineChars[i] == '!') {
            needCapital = true;
        }

        //Add character to string
        output += lineChars[i];
    }

    //Output string
    System.out.println (output);
}
}