java - 如果字符串是某个字母,我如何获取用户输入并用某个字符替换字符串的最后 2 位数字
问题描述
我对此有点挣扎。到目前为止,我已经能够接受用户输入,但我不确定在替换最后 2 位数字(如果它们是“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
长度相同,否则您会遇到问题。
相反,首先删除方法的输入参数,因为它会让您感到困惑。替换使用str
withreadInput
并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());
}
}
推荐阅读
- python - 发送 JSON 文件以响应请求,Flask
- django - 部署到 Heroku 的 Django 应用程序 - psycopg2.errors.NotNullViolation 因为数据未通过 Ajax
- java - 如何命名下载的数据:文件?
- typescript - 如何在插件 InAppBrowser(Ionic 3) 的工具栏中添加标题?
- shopify - 我怎样才能获得价值Shopify 响应式?
- javascript - 如何使用 Vanilla Javascript 检查标签中是否包含图像?
- c# - 在 C# 中使用 Exchange ActiveSync
- javascript - GreaseMonkey - 防止在线脚本
- python - 我似乎无法在没有错误的情况下在 django 中使用 DateTimeField
- android - 找不到明确的活动类 {...}; 您是否在 AndroidManifest.xml 中声明了此活动?