gpt4 book ai didi

java - 使用 substring() 和 charAt() 检查字符串是否为回文

转载 作者:行者123 更新时间:2023-12-02 06:15:23 26 4
gpt4 key购买 nike

我的代码应该要求用户输入一个字符串,然后使用 charAt()substring() 方法检查它是否是回文。我相信,我已经正确完成了所有操作,但 NetBeans 编译不正确。

当我运行代码时,NetBeans 告诉我:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
at palindrome.Palindrome.methodA(Palindrome.java:31)
at palindrome.Palindrome.main(Palindrome.java:27)
Java Result: 1

那么,基本上它说我缺少返回语句?我不明白这怎么可能。

任何帮助将不胜感激。谢谢。

package palindrome;

import java.util.Scanner;

public class Palindrome {

/**
* Program asks user to enter a string.
*/
public static void main(String[] args) {
String userInput; //user-inputted String
String result;

//set up instance of Scanner for user input
Scanner scan = new Scanner(System.in);

//ask user for input
System.out.print("Please enter a String: ");
userInput = scan.nextLine();

//run methodA
result = methodA(userInput);

}

public static String methodA(String inString) {
/*
* This method checks the user-inputted String against a backward copy
* of itself using only String and Character methods.
*/

//next two int variables used as int pointers for first letter of String
//and last letter of user-inputted String
int begPoint = 0;
int endPoint = inString.length() - 1;

//define Strings to return to main method
String isPal = (inString + " is a palindrome!");
String notPal = (inString + " is not a palindrome.");

while (begPoint < endPoint) {
//two substrings defined to test String character for character
String firstChar = inString.substring(begPoint, begPoint + 1);
String lastChar = inString.substring(endPoint, endPoint + 1);

//algorithm continues step by step with begPoint going up one and
//endPoint decreasing by one
begPoint++;
endPoint--;

//basically here I am trying to check the characters of the user-
//inputted Strings using the charAt methods but I'm lost when I
//get to this point
if (inString.charAt(begPoint) == inString.charAt(endPoint)) {
return isPal;
} else {
return notPal;
}
}
}
}

经过一些回答后——我现在将 while 语句更改为:

while(begPoint<endPoint) {
//two substrings defined to test String character for character
String firstChar = inString.substring(begPoint, begPoint + 1);
String lastChar = inString.substring(endPoint, endPoint + 1);

//basically here I am trying to check the characters of the user-
//inputted Strings using the charAt methods
if (inString.charAt(begPoint) == inString.charAt(endPoint)) {
return isPal;
} else {
return notPal;
}

//algorithm continues step by step with begPoint going up one and
//endPoint decreasing by one
begPoint++;
endPoint--;
}

但是,现在它告诉我 (begPoint++) 是一个无法访问的语句。

最佳答案

您的问题是您在检查 charAts 之前移动了 begPoint 和 endPoint。将 begPoint 和 endPoint 前移的代码移至使用 charAt 方法之后。

关于java - 使用 substring() 和 charAt() 检查字符串是否为回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21541928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com