java - 如何使用户可以替换他们输入的句子可以在Java中替换

标签 java

所以我试图让程序询问用户以下问题并得到以下答案:

例如: 输入下面的第二句话: 这是一本书(用户输入的) 选择您要替换的字符串: 书(用户输入此) 选择将在替换中使用的新字符串: 汽车(用户输入此) 替换后的文字是:这是一辆车。

import java.util.*;
import java.util.Scanner;

public class StringManipulation {

public static void main(String[]args) {

    /*This is where the user can type a second sentence*/
    System.out.println("Type a 2nd Sentence Below:");
    Scanner sd = new Scanner(System.in);
    String typingtwo = sd.nextLine();

    String sending;
    /*Here the program will tell the user a message*/
    System.out.println("This is your sentence in capital letters:");
    sending = typingtwo.toUpperCase();
    System.out.println(sending);
    /*Here the program will tell the user another message*/
    System.out.println("This is your sentence in lower letters:");
    sending = typingtwo.toLowerCase();
    System.out.println(sending);

    System.out.print("Your Token Count:");
    int FrequencyTwo = new StringTokenizer(sending, " ").countTokens();
    System.out.println(FrequencyTwo);

    String charactertwo = new String(typingtwo);
    System.out.print("Your Character Length:");
    System.out.println(charactertwo.length());

    String repWords;
    String newWord;
    String nwords;
    String twords;
    System.out.println("Choose what string of characters do you want to    
replace");
    repWords = sd.next();
    System.out.println("Choose what new string will be used in the replacement");
    nwords = sc.next();
    twords = typingtwo.replace(repWords,nwords);
    System.out.printf("The text after the replacement is: %s \n",nwords);

}
  }

我已经尝试了一切,但由于某种原因,我只得到他们最后选择的词。请帮忙!

最佳答案

尝试使用Scanner.nextLine而不是Scanner.next

引用Java API文档了解两者的区别

这是另一个问题:

twords = typingtwo.replace(repWords,nwords);
System.out.printf("The text after the replacement is: %s \n",nwords);

您正在打印 nwords 而不是 twords

关于java - 如何使用户可以替换他们输入的句子可以在Java中替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52232511/

相关文章:

java - GWT:解析 CSS 样式属性

java - 服务器客户端多线程

java - SonarQube Scanner - 插件下载之间的长时间停顿

java应用程序在 "info"模式下运行良好,在Logback的 "debug"模式下抛出异常

java - 如何找到在字符串中至少出现两次且不重叠的任意两个字母对

java - 在 Ubuntu 中构建 Red5 应用程序失败

java - 如何在java中编写递归方法,接受正整数或负整数并返回其位数

java - Lotus Domino Server 不返回任何 Java View (getViews 为空)

java - 如何在 Spring 中注入(inject)一个 List 实例?

java - 如何从自定义 View 引用同一 Activity 中的按钮