INeedHelp101
INeedHelp101

Reputation: 107

Identify specific characters in a String and remove it - Doesn't work

This program is supposed to take a user input and remove any digits found in it, but clearly, something is wrong.

private static String removeNum(String inp)
{
    String newInp = new String();
    char[] inpChars = inp.toCharArray();

    for(char output:inpChars)
    {
        if(output==0 || output==1 || output==2 || output==3 || output==4 || output==5 || output==6 || output==7 || output==8 || output==9)
        {

        }
        else
        {
            newInp += output;
        }
    }
    return newInp;
}

public static void main(String[] args)
{
    EasyReader console = new EasyReader();
    System.out.print("Enter input: \n");
    String inp = console.readLine();
    System.out.print("Output: \n");
    System.out.print(removeNum(inp));
}

Upvotes: 0

Views: 68

Answers (4)

MW600
MW600

Reputation: 43

You can actually spare most of the code and use regex:

private static String removeNum(String inp) {
    return inp.replaceAll("[0-9]","");
}

Upvotes: 3

Dragondraikk
Dragondraikk

Reputation: 1679

You are making an incorrect comparison by comparing char with int.

instead of

if(output==0 || output==1 || ...

you should use

if(output=='0' || output=='1' || ...

Upvotes: 4

Daniel Gabriel
Daniel Gabriel

Reputation: 3985

You should put each digit in your if statement into single quotes, like this: if (output == '0' || output == '1' ... ).

You can also use a more efficient condition instead: Character.isDigit(output). In this case the whole condition will look like this:

if (Character.isDigit(output)) {
    ...
}

Upvotes: 2

user4759923
user4759923

Reputation: 531

Put single quotes around the digits. Without them, you do not refer to the character you want, but to the one with the specified number.

Upvotes: 1

Related Questions