所以我试图让程序询问用户以下问题并得到以下答案:
例如: 输入下面的第二句话: 这是一本书(用户输入的) 选择您要替换的字符串: 书(用户输入此) 选择将在替换中使用的新字符串: 汽车(用户输入此) 替换后的文字是:这是一辆车。
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/