簡體   English   中英

在Java中使用遞歸反轉句子

[英]Reversing a sentence using recursion in java

我正在嘗試使用遞歸來反轉句子並將其向后打印出來。 現在,它提示我輸入一個句子后,它不允許我輸入任何內容並結束。 sc.nextLine()有問題嗎? 如何輸入一個句子作為字符串。

private static void testNum3() 
    {
        System.out.print("Type in a sentence:");
        String sentence= sc.nextLine();
        System.out.println(reverse(sentence));

    }

    public static String reverse (String sentence)
    {
        if (sentence.length()== 0) 
            return sentence;

        return reverse(sentence.substring(1)) + sentence.charAt(0);
    }

我在其他地方使用sc.next()。 他們都必須一樣嗎?

否,但是您必須注意正確處理EOL或“行尾”令牌。 如果調用sc.next()並留下一個懸空的EOL令牌,則下次調用sc.nextLine()時,它將被“吞噬”,從而阻止您獲取輸入。

一種解決方案:需要處理EOL令牌時調用sc.nextLine()

例如,如果您從用戶那里獲取一個int信息,並且它是唯一輸入到行中的東西,那么有時您必須這樣做:

int myVar = sc.nextInt();
sc.nextLine();  // swallow dangling EOL token with this call

// now you can safely call this below
String myString = sc.nextLine();

試一試

import java.io.IOException;
import java.util.Scanner;

public class CoreJavaTest {

    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        String sentence = "";
        while (true) {
            System.out.print("Enter sentence:");
            sentence = sc.nextLine();

            if (sentence.equals("exit")) {
                System.out.println("Exiting...");
                break;
            }

            reverse(sentence);
            System.out.println("");
        }

    }

    public static void reverse(String args) {
        if (args.length() != 0) {
            System.out.print(args.charAt(args.length() - 1));
            reverse(args.substring(0, args.length() - 1));
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM