我对此有点挣扎。到目前为止,我已经能够接受用户输入,但我不确定在替换最后两个数字(如果它们是"x")时我做错了什么。
class Main
{
public static String problem1_removeChars(String str) {
Scanner myScanObj = new Scanner(System.in); //Create Scanner Object
System.out.println("Enter your string: ");
String readInput = myScanObj.nextLine(); //Read The Input
System.out.println("Your String Is: " + readInput);
int stringLength = readInput.length(); // Takes length of the users input
if(stringLength >= 2) {
if (str.charAt(stringLength - 2) == 'x') {
str = str.substring(0, stringLength - 2) + str.charAt(stringLength - 1);
}
}
if (str.length() >= 1) {
if (str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
}
// IF the last 2 characters are 'x' THEN replace 'x' with '~nothing~' to remove x
// return the string!
return "str"; // FIX ME
}
public static void main(String[] args) {
System.out.println(problem1_removeChars("str"));
}
}
主要问题是您基本上忽略了用户输入(除了读取String
的长度)
因此,除非str
和readInput
的长度相同,否则您将遇到问题。
相反,从删除方法的输入参数开始,因为这会让您感到困惑。用readInput
替换str
的使用,并在结束时返回readInput
import java.util.Scanner;
public class Main {
public static String problem1_removeChars() {
Scanner myScanObj = new Scanner(System.in); //Create Scanner Object
System.out.println("Enter your string: ");
String readInput = myScanObj.nextLine(); //Read The Input
System.out.println("Your String Is: " + readInput);
int stringLength = readInput.length(); // Takes length of the users input
if (stringLength >= 2) {
if (readInput.charAt(stringLength - 2) == 'x') {
readInput = readInput.substring(0, stringLength - 2) + readInput.charAt(stringLength - 1);
}
}
if (readInput.length() >= 1) {
if (readInput.charAt(readInput.length() - 1) == 'x') {
readInput = readInput.substring(0, readInput.length() - 1);
}
}
// IF the last 2 characters are 'x' THEN replace 'x' with '~nothing~' to remove x
// return the string!
return readInput; // FIX ME
}
public static void main(String[] args) {
System.out.println(problem1_removeChars());
}
}
if (readInput.endsWith("xx")) {
readInput = readInput.substring(0, readInput.length() - 2);
}
肯定够了吗?
简单的解决方案是这样做:
if (readInput.endsWith("xx"))
return readInput.substring(0, readInput.length() - 2);
else
return readInput;
您也可以使用regex:
return readInput.replaceAll("xx$", "");