2

我是 Java 新手,想交换两个输入到程序中然后保存为字符串的单词。我包含了一个 if 语句,以确保输入了我要切换的两个单词。

  Scanner in = new Scanner(System.in);
  System.out.println("Please enter at least one thing you love and one thing you hate using the words hate and love: ");
  String loveHate = in.nextLine();



  if (loveHate.indexOf( "love" ) == -1 || loveHate.indexOf( "hate" ) == -1 ){
    System.out.println("Please include the words love and hate.");
    return; 
  }

我想取用户输入的句子并切换爱和恨这两个词,然后用切换的词重新打印一个新字符串。

4

1 回答 1

3

一种粗略的方法,前提是您不希望输入中的文本“xxxx”是标准交换:

...
String loveHate = in.nextLine();

String hateLove = loveHate.replaceAll("love", "xxxx");
       hateLove = hateLove.replaceAll("hate", "love");
       hateLove = hateLove.replaceAll("xxxx", "hate");

System.out.println("Changed "+loveHate+" into "+hateLove);
于 2012-09-26T22:19:30.360 回答