如何从字符串中过滤数字的某些值并返回其余值



我需要创建一种将字符串作为输入的方法,例如"我在37 Wilderness中有2456个气球",如果将N设置为3,则将"更多"设置为false,该方法将返回"我在荒野中有2个气球"。如果有更多设置为真,它将返回"我有456个气球在7荒野"

我已经玩了很多滤波器,但是我不知道如何将此方法放在一起。这是我到目前为止提出的:

public class Test1
{
    public static void main(String [] args)
    {
        List<Integer> lst= new ArrayList<Integer>();
        //Take user input any number of times based on your condition.
        System.out.println("Please enter a number :");
        Scanner sc= new Scanner(System.in);
        int i= sc.nextInt();
        if(i==0 || i==1 || i==2 ||i==3)
        {
            lst.add(i);
        }
        //Go back
    }
}

或我可以使用这样的东西:

int input;
do {
    input = sc.nextInt();
} while (input < 0 || input > 3);

我是Java的新手,所以这项任务的进展一直很慢

如何获得此方法来保存字母和过滤数字,具体取决于两个值(一个数字和true/forse(?

这是一个简单的解释解决方案。请注意,我们使用了非常简单的方法,但仍然需要大量验证。另外,还有较短的解决方案,但这是我写的一种解决方案,因此对于Java中的新人来说更清楚。

public static void main(String[] args) {
    Scanner sc= new Scanner(System.in);
    System.out.println("Enter your string: ");
    String strInput = sc.nextLine();
    System.out.println("Enter n: ");
    int n = sc.nextInt();
    System.out.println("Do you want more? (Y/N)");
    char more = sc.next().charAt(0);
    String result = "";
    // Loop through all the characters in the String
    for(char c : strInput.toCharArray()) {
        // Check if the character is a number
        // If not, just append to our result string
        if(!Character.isDigit(c)) {
            result += c;
        } else {
            // Converts character to the number equivalent value
            int numValue = Character.getNumericValue(c);
            // If more is 'Y', we check if it's greater than the number and append
            // else if more is 'N', we check if the value is less than n then append.
            // Otherwise, do nothing.
            if (more == 'Y' && numValue > n) {
                result += c;
            } else if (more == 'N' && numValue < n) {
                result += c;
            }
        }
    }
    System.out.println(result);
}

最新更新