gpt4 book ai didi

java - 使用 Java 和 HTML 获取两个字符串输入之和的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-01 18:34:26 25 4
gpt4 key购买 nike

我正在尝试制作一个 HTML 页面,其中用户输入 2 个数字作为字符串,单击“提交”,然后显示总和。我在解析时搞砸了一些东西,我不知道如何纠正它。如何解决这个问题?

java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
java.base/java.lang.Float.parseFloat(Float.java:461)
basicaddition.BasicAddition.processRequest(BasicAddition.java:42)

代码:

    String EmptyError = "";
String FirstNumber = request.getParameter("FirstNumber");
String SecondNumber = request.getParameter("SecondNumber");

float firstNumber = Float.parseFloat(FirstNumber);
float secondNumber = Float.parseFloat(SecondNumber);

if(FirstNumber.isBlank() && SecondNumber.isBlank())
{
EmptyError = "There is no sum";
}

else {
try {
firstNumber = Float.parseFloat(FirstNumber);

} catch (NumberFormatException ex) {
EmptyError = "Value is not a number";
}

try {
secondNumber = Float.parseFloat(SecondNumber);

} catch (NumberFormatException ex) {
EmptyError = "Value is not a number";
}


}

Float Result = firstNumber + secondNumber;

response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet BasicAddition</title>");
out.println("</head>");
out.println("<body>");

out.println("<h1>Returns the sum of two numbers, ");
out.println("</h1>");

out.println("<input type='text' name='FirstNumber' />");
out.println(EmptyError);

out.println("<input type='text' name='SecondNumber' />");
out.println(EmptyError);

out.println("<input type='submit' value='Get the sum' />");
out.println(EmptyError);
out.println(Result);


out.println("<h1>Servlet BasicAddition at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");

最佳答案

我发现您正在尝试解析条件之前的数字!

float firstNumber = Float.parseFloat(FirstNumber);
float secondNumber = Float.parseFloat(SecondNumber);

这两行抛出异常,因为 FirstNumber 和 SecondNumber 不是有效数字!

关于java - 使用 Java 和 HTML 获取两个字符串输入之和的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60086217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com