Failed to convert value of type 'java.lang.String' to required type 'double'; nested exception is java.lang.NumberFormatException: empty String

Sharman Jeurkar

I am new to Spring boot. I am trying to calculate moles when the user inputs 2 of the three values. I have tried to make a dropdown, where if one of the link is clicked , then one of the textbox becomes read-only. But while doing this I am getting this error

 There was an unexpected error (type=Bad Request, status=400).
    Failed to convert value of type 'java.lang.String' to required type 'double'; nested exception is java.lang.NumberFormatException: empty String
Failed to convert value of type 'java.lang.String' to required type 'double'; nested exception is java.lang.NumberFormatException: empty String
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'double'; nested exception is java.lang.NumberFormatException: empty String
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: java.lang.NumberFormatException: empty String
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
    at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.base/java.lang.Double.parseDouble(Double.java:556)
    at java.base/java.lang.Double.valueOf(Double.java:519)
    at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:223)
    at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115)
    at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:429)
    at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:402)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:155)
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:73)
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:53)
    at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:700)
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:125)
    ... 47 more

This is my Java controller code:

package com.sharman.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.sharman.service.Calculator;

@Controller
@RequestMapping("/Chemistry-Calculator/")
public class HomeController {
    @RequestMapping("/")
    public String callHome() {
        return "home";
    }

    @RequestMapping("/about")
    public String callAbout() {
        return "about";
    }

    @RequestMapping("/Mole-Calculator")
    public String callMoleCalculator() {
        return "Mole-Calculator";
    }

    @RequestMapping("/Number-Of-Moles")
    public String calculateMoles(@RequestParam(value = "givenMass",  required=false) double givenMassInput,
            @RequestParam(value = "molarMass",  required=false) double molarMassInput,
            @RequestParam(value = "moles",  required=false) double molesInput, Model model) {

        Calculator calculate = new Calculator();

        if (molesInput == 0) {
            double moles = calculate.calculateMoles(givenMassInput, molarMassInput);
            model.addAttribute("givenMass", givenMassInput);
            model.addAttribute("molarMass", molarMassInput);
            model.addAttribute("moles", moles);
            
        }else if (givenMassInput == 0) {
            double givenMass = calculate.calculateGivenMass(molarMassInput, molesInput);
            model.addAttribute("molarMass", molarMassInput);
            model.addAttribute("moles", molesInput);
            model.addAttribute("givenMass", givenMass);
        }else if (molarMassInput == 0) {
            double molarMass = calculate.calculateMolarMass(givenMassInput, molesInput);
            model.addAttribute("givenMass", givenMassInput);
            model.addAttribute("moles", molesInput);
            model.addAttribute("molarMass", molarMass);
        }

        return "Mole-Calculator";
    }

    @RequestMapping("/Avagadros-Number")
    public String callAvagadrosNumber() {
        return "Avagadros-Number";
    }

    @RequestMapping("/Avagadro's-Number-Result")
    public String calculateAvagadrosNumber(@RequestParam(value = "moles") double moles, Model model) {

        Calculator calculate = new Calculator();
        double result = calculate.calculateAvagadrosNumber(moles);
        String power = "10\u00b2\u00b3";
        System.out.println(power);
        model.addAttribute("result", result + "x" + power);
        model.addAttribute("moles", moles);
        return "Avagadros-Number";
    }

}

I am here trying to send the values in a model variable. This is my jsp page:

<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link
    href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
    rel="stylesheet"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
    crossorigin="anonymous">

<title>Mole Calculator | Chemistry Calculator</title>

</head>



<body>

    <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-black">

        <div class="container-fluid">
            <a class="navbar-brand" href="#"><h4>
                    <b>Chemistry Calculator</b>
                </h4></a>

            <button class="navbar-toggler" type="button"
                data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
                aria-controls="navbarSupportedContent" aria-expanded="false"
                aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">

                <ul class="navbar-nav  text-uppercase">

                    <li class="nav-item"><a class="nav-link active"
                        aria-current="page" href="/Chemistry-Calculator/">Home</a></li>

                    <li class="nav-item"><a class="nav-link active"
                        aria-current="page" href="/Chemistry-Calculator/about">About</a></li>


                </ul>

            </div>
        </div>
    </nav>

    <div class="container" style="padding-top: 5%;">

        <div class="card px-4 py-5" style="width: 650px;">
            <div class="card-block">

                <form action="/Chemistry-Calculator/Number-Of-Moles">

                    <div class="mb-3">
                        <label for="givenMass" class="form-label">Given Mass of
                            Substance</label> <input type="number" class="form-control" id="givenMass"
                            aria-describedby="emailHelp" name="givenMass"
                            value="${givenMass}" style="width: 600px">
                    </div>
                    <div class="mb-3">
                        <label for="molarMass" class="form-label">Molar Mass</label> <input
                            type="number" class="form-control" id="molarMass" name="molarMass"
                            value="${molarMass}" style="width: 600px">
                    </div>

                    <div class="mb-3">
                        <label for="moles" class="form-label">Moles</label> <input
                            type="number" class="form-control" id="moles" name="moles"
                            value="${moles}" style="width: 600px">
                    </div>

                    <input class="btn btn-outline-success" type="submit"
                        value="Calculate">

                    <div class="btn-group">
                        <button type="button" class="btn btn-success dropdown-toggle"
                            data-bs-toggle="dropdown" aria-expanded="false">Choose
                            what to calculate</button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" onclick="readonlyForMoles()"
                                href="#">Calculate Moles</a></li>
                            <li><a class="dropdown-item"
                                onclick="readonlyForMolarMass()"
                                href="#">Calculate Molar
                                    Mass</a></li>
                            <li><a class="dropdown-item"
                                onclick="readonlyForGivenMass()"
                                href="#">Calculate Given
                                    mass</a></li>
                        </ul>
                    </div>

                </form>
            </div>
        </div>
    </div>

    <script
        src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
        crossorigin="anonymous"></script>
    <script type="text/javascript"src="/javascript/script.js"></script>

</body>
</html>

Please help me sove this error

Hopey One

Make the parameters Double (class type) rather than double primitive type. I think spring will then convert an empty string from your form request (or no parameter) to a null rather than throwing an exception.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is java.lang.NumberFormatException: For input string: ""

MismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException

Spring NumberFormatException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long

nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type

Spring @Value TypeMismatchException:Failed to convert value of type 'java.lang.String' to required type 'java.lang.Double'

Failed to convert value of type java.lang.Double to String

@Value -> Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'

Failed to convert value of type 'java.lang.String' to required type 'int'; For input string: "save"

Failed to convert value of type 'java.lang.String' to required type 'java.sql.Date'

Failed to convert value of type 'java.lang.String' to required type 'java.util.Date' on swagger

Failed to convert property value of type java.lang.String[] to required type java.util.List

MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int';

Spring/Thymeleaf - Failed to convert value of type 'java.lang.String' to required type

Failed to convert property value of type 'java.lang.String' to required type '[]'

Spring MVC - Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer'

Cannot convert value of type 'java.lang.String' to required type - java.lang.IllegalStateException:

Failed to convert a value of type java.lang.String to long

Failed to convert a value of type java.lang.String to int?

Failed to convert property value of type 'java.lang.String'

Firestore Failed to convert value of type java.lang.String to Date

Failed to convert property value of type [java.lang.String]

Failed to convert a value of type java.lang.String to int

Firebase:Failed to convert value of type java.lang.Boolean to String

Resolved [org.springframework.beans.TypeMismatchException String : Failed to convert value of type 'java.lang.String' to required type

Model.addAttribute : Failed to convert value of type 'java.util.Arrays$ArrayList' to required type 'java.lang.String'

Failed to convert value of type 'java.lang.String' to required type 'java.util.Date' when sending GET request

Thymeleaf and SpringBoot - Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for prope

Failed to convert property value of type 'java.lang.String' to required type 'com.ujazdowski.SocialPortal.model.tables.User'

How to convert value of type 'java.lang.String' to required type 'java.util.Date'?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive