如何使用递归来反转文本? [英] How to use recursion to reverse text?

查看:39
本文介绍了如何使用递归来反转文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.*;
public class RecursionProject {
  public static void main(String[]args) {
    getLine(); 
    useRecursion();
  }
  public static void getLine() {

    System.out.println("This program uses recursion.") ;
    System.out.println("Would you like to see how it works?") ;
    System.out.print("If yes, type yes, else type no -----> ");
    String userResponse = null;
    Scanner in = new Scanner(System.in);
    userResponse = in.next();
    System.out.println(userResponse);
    if (userResponse.equalsIgnoreCase("yes")) {
      System.out.println() ;
    }
    else {
      System.out.println("Thank you for using this program.");
      System.exit(0);
    }

  }
  private static void useRecursion(){
    System.out.println("Type in what you would like to see") ; 
    System.out.println("done recursively. (This program ") ;
    System.out.println("excludes white spaces):") ;
    String s = null ; 
    Scanner console = new Scanner(System.in) ;
    s = console.next() ; 
    if (s.isEmpty()) {
      System.out.print(" - ") ;

    }
    else {
      System.out.println("0") ;
    }
  } 
}

这是我目前的代码.我的任务是从控制台读取输入,然后使用递归反转相位.即如果用户输入animals",它会在屏幕上打印出slamina".我知道我的基本情况是该行是否为空,而我的递归情况是该行中是否包含文本.这是一个 Programming 2 类,在 Eclipse 4.2.2 上使用 Java

SO this is my code so far. My assignment is to read input from console, then reverse the phase using Recursion. i.e. if the user typed "animals" it would print out "slamina" to the screen. I understand that my base case is if the line is empty and my recursive case is if the line has text in it. This is a Programming 2 class, using Java on Eclipse 4.2.2

推荐答案

通常使用递归,您会有一个调用自身的函数.你不需要递归来反转字符串,但我想你可以有一个函数,它接受一个字符串,并将字符串的第一个字符附加到其余字符的反向.

Normally with recursion you'd have a function that calls itself. You don't need recursion to reverse a string, but I suppose you could have a function that takes a string, and appends the first character of the string to the reverse of the rest.

我将尝试解释这是如何工作的,而不会提供太多代码.

I'll try to explain how this works without giving too much code.

假设您有一个函数 reverse 可以反转字符串.你可以在其中说:

So say you had a function reverse that reverses a string. In it you could say something like:

return reverse(myString.substring(1)) + myString[0];

当你在字符串 Hello 上调用它时,它是这样工作的:

When you call it on the string Hello, it works like this:

reverse("Hello")
-> reverse("ello") + "H"
-> reverse("llo") + "e" + "H" 
-> reverse("lo") + "l" + "e" + "H" 
-> reverse("o") + "l" + "l" + "e" + "H" 
-> "o" + "l" + "l" + "e" + "H"

需要在字符串为空时截断递归.

It needs to cut off the recursion when the string is empty.

这篇关于如何使用递归来反转文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆