首页 > 解决方案 > 如果字符串是某个字母,我如何获取用户输入并用某个字符替换字符串的最后 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"));
    }
}

标签: javastring

解决方案


主要问题是您基本上忽略了用户输入(除了读取 的长度String

因此,除非strreadInput长度相同,否则您会遇到问题。

相反,首先删除方法的输入参数,因为它会让您感到困惑。替换使用strwithreadInputreadInput在最后返回

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());
    }
}

推荐阅读