简体   繁体   中英

Print all odd and even numbers input using toCharArray()

I want to get all of the odd and even numbers on the user's input and then get the product of all the odd numbers and the difference in even numbers. For example: Enter a string: dfgi456456=';]=34521. The output should display all odd and even numbers in the user input and the product and difference, in this case ODD numbers are: 5,3,1 EVEN numbers are: 4,6,2 PRODUCT(answer to multiplication) of ODD numbers:15 DIFFERENCE(answer to subtraction) of EVEN numbers: -4. Kindly look at my code below. Any help would be appreciated. Thanks.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

    if (request.getParameter("stringToArray") != null) {
        char[] input = request.getParameter("stringToArray").toCharArray();
        int diffEven;
        int prodOdd;
        int i;
        for(i = 0; i <= input.length; i++){
             if( i % 2 == 0){
                 diffEven -= input;
             }
             else{
                 prodOdd *= input;
             }
        }
        out.print("<h4>All ODD numbers are: </h4>" +i);
        out.print("<h4>All EVEN numbers are: </h4>" +i);
        out.print("<h4>Product of all ODD numbers: </h4>" +prodOdd);
        out.print("<h4>Difference of all EVEN numbers: </h4>" +diffEven);
    }
    out.close();

}

}

  1. Proper way of accessing an array element is index[i] .
  2. Array elements are char typed. In order to do arithmetic tests and calculations you should convert them to int values. Character.getNumericValue(input[i]) might help. You should also test this to be non-negative, since it returns negative values for non-digit characters.
  3. For multiplication part, initial value of prodOdd is 0 . Thus all your multiplications go to waste. You should initialize this variable with 1 .
  4. For difference part, you want the first number not to be subtracted. So you should have a flag or something to detect first digit encountered in input. Something like that might help:
boolean firstNum = true; 
    ... 
    if ( ... ) {
        // Even numbers
        if (firstNum)
        {
            diffEven += digitVal;
            firstNum = false;
        }
        else 
        {
            diffEven -= digitVal;
        } 
    }

Here is a code snippet to extract distinct numbers from the string:

static IList<int> ExtractNumbers(string data)
{
    var result = string.Empty;
    var regex = new Regex(@"\d+", RegexOptions.None);
    var matches = regex.Matches(data);

    foreach (Match match in matches)
    {
        result += match.Value;
    }

    return result
        .ToCharArray()
        .Distinct()
        .Select(x => int.Parse(x.ToString()))
        .ToList();
}

From there, you should be able to use Linq to get your odd/even numbers:

var numberData = "dfgi456456=';]=34521";
var numbers = ExtractNumbers(numberData);
var oddNumbers = numbers.Where(x => x % 2 == 0).ToList();
var evenNumbers = numbers.Where(x => x % 2 != 0).ToList();

From that list, you can iterate through the numbers to get your products/differences/whatever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM