在Java中交换单词

时间:2012-09-26 22:16:05

标签: java

我是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; 
  }

我想接受用户输入的句子并切换单词love and hate然后重新打印带有单词切换的新字符串。

1 个答案:

答案 0 :(得分: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);