java - 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;
}
}
解决方案
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()
推荐阅读
- python - 全屏的 PyQtWebEngine 是 Flash 屏幕
- angular - 如何从 ViewContainerRef - Angular 9 获取子组件?
- javascript - 如何等待函数的返回值
- azure-pipelines - 如何在 Azure 管道中的 vstest 任务中提供多个测试类别
- android - 执行 com.simligility.maven.plugins:android-maven-plugin:4.6.0: javax/xml/bind/annotation/XmlSchema 时缺少必需的类
- excel - 有没有一种更快的方法可以使用 Excel VBA 将日期添加到某个未来日期
- react-native - 只创建一个始终使用 react-i18next 翻译其内容的 Text 组件是不是一个坏主意?
- php - isset 功能不起作用。块内的代码执行
- php - 如何使用 php 将 Mailchimp API 3.0 的“购物车”和“购物车行”添加到自定义商店?
- django - 启动 celery .delay 后 Django 冻结。怎么修?