Java 字符串到数组并将某个单词从用户名替换为大写

Java string to array and replace a certain word from user to uppercase

这是完整的问题: ... 我的代码

import java.util.Scanner;

import java.lang.StringBuilder;

public class javaAPIString {

    public static void main(String[]args) 
    {
        String SentenceFromUser = "";
        String IndiWordFromUser = "";
    /// String upper = IndiWordFromUser.toUpperCase();
        //String[] words = SentenceFromUser.split("\s+");

        char ans;   

          Scanner keyboard = new Scanner(System.in);
          do
            {
              final StringBuilder result = new StringBuilder(SentenceFromUser.length());
              String[] words = SentenceFromUser.split("\s");
              System.out.println("Enter a sentence :");
              SentenceFromUser = keyboard.nextLine();

              System.out.println("Enter a word : ");
              IndiWordFromUser = keyboard.next();
       ///    IndiWordFromUser = upper;

              for(int i =0; i > words.length; i++ )
              {
                  if (i > 0){
                        result.append(" ");
                        }   
                        result.append(Character.toUpperCase(words[i].charAt(0))).append(
                                    words[i].substring(1)); 
              }

      //    System.out.println("The Output is : " + SentenceFromUser);


              System.out.println("Do you want to enter another sentence and word ? If yes please type 'Y' or 'y'.");
              ans = keyboard.next().charAt(0);
            }
            while ((ans == 'Y') || (ans == 'Y')); 
    }
}

我的代码输出/问题: 输入一句话: 我喜欢饼干 输入一个词: 饼干 输出是:我喜欢饼干 你想输入另一个句子和单词吗?如果是,请输入 'Y' 或 'y'。

它returns相同的原始句子,无需更改第二个输入的大写以替换为所有大写。

只是一些事情:

  1. 请使用 java 变量名称的命名约定
  2. 当您执行代码时,此指令将用空字符串覆盖用户输入。

    IndiWordFromUser = 上层;

  3. String[] words = SentenceFromUser.split("\s");...你第一次拆分一个空字符串,另一个运行旧句子

  4. 从未读取变量 IndiWordFromUser

希望我的解决方案对您有所帮助! :)

import java.util.Scanner;

public class Solution {

    private static Scanner in = new Scanner(System.in);

    public static void main(String[] args) {
       getTextFromUser();
    }

    private static void getTextFromUser() {
       print("Enter Sentence Here: ");
       String text = in.nextLine();

       print("\nDo you want to capitalize words in sentence? Y/N: ");

       while (in.nextLine().equalsIgnoreCase("y")) {
           print("Enter Word: ");
           print("Modified Text: " + changeWord(text, in.nextLine()));
           print("\n\nDo you want to capitalize words in sentence? Y/N");
       }
    }

    private static String changeWord(String text, String word) {
        return text.replaceAll("\b" + word + "\b" /* \b Means word 
        boundary */, word.toUpperCase()); // No validations done.
    }

    private static void print(String message) {
        System.out.print(message);
    }

}