首页 > 解决方案 > java在else语句中的方法中返回一个字符串

问题描述

我需要从主方法返回toscanText字符串,scanText()但我无法找到从 else 语句中返回该字符串的方法。


import java.util.*;
import java.io.*;

public class ReverseString {

    public static void main(String[] args) {
        System.out.println("Debug check");
        String scannedString = scanText();

    }

    public static String scanText() {
        System.out.println("Enter the string");
        Scanner scanner = new Scanner(System.in);
        String toScanText = scanner.next();
        int stringLength = toScanText.length();

        if (stringLength == 0) {
            System.out.println("Enter the string again");
            scanText();
        }else if(stringLength>0){
            return toScanText;
        }


    }

    public static String reverseMethod(String toReverseString){


        System.out.println("debug check");
        toReverseString="this string";
        return toReverseString;
    }
}

标签: java

解决方案


public static String scanText() {
    boolean noValidString = true;
    System.out.println("Enter the string");
    Scanner scanner = new Scanner(System.in);

    while(noValidString) {
        String toScanText = scanner.next();

        if (toScanText.length(); == 0) {
            System.out.println("Enter the string again");
        } else {
            noValidString = false;
    }
    return toScanText;
}

我的原始方法没有引入新概念。这里不需要递归方法调用。此外,扫描仪应在return使用前的某个时间点关闭scanner.close()


推荐阅读