gpt4 book ai didi

java - 当用户输入 "0"时显示错误消息,无法退出 "error"消息

转载 作者:行者123 更新时间:2023-11-29 06:34:05 25 4
gpt4 key购买 nike

知道如何解决这个问题吗?我告诉用户输入他想要平均的数字数量。当然,正如您在代码中看到的那样,如果他输入 0 或负数,我希望它标记用户输入另一个非 0 或负数的数字。问题是,一旦用户输入 0 或负数,它就会卡在那个状态,我必须终止程序。

帮忙吗?

import javax.swing.JOptionPane;

public class TestProgTres
{
public static void main(String[] args)
{
//Variable Declaration
String ShowSome;
String ShowSomeAgain;
int z = 0;
double avg = 0;
double totalamt = 0;

ShowSome = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
double AllNumbers = Double.parseDouble(ShowSome);

while (AllNumbers < 1)
{
JOptionPane.showInputDialog("You cannot enter a negative or a 0. Enter the amount of numbers you would like to average");
AllNumbers = Double.parseDouble(ShowSome);
}//end while

if (AllNumbers > 0)
{
double Numbers [] = new double [(int) AllNumbers];

for (z = 0; z < Numbers.length; z++)
{
ShowSomeAgain= JOptionPane.showInputDialog("Enter number " + (z + 1));
Numbers[z]=Double.parseDouble(ShowSomeAgain);

totalamt += Numbers[z];
avg = totalamt/AllNumbers;
}
}

JOptionPane.showMessageDialog(null, "The of the numberes entered is " + avg);
}//end main
}// end class

最佳答案

嗯,它不是最干净的,但它有一个相当重要的错误,

ShowSome = JOptionPane.showInputDialog("Enter the amount of numbers "
+ "you would like to average");
double AllNumbers = Double.parseDouble(ShowSome);

while (AllNumbers < 1)
{
JOptionPane.showInputDialog("You cannot enter a negative or a 0. "
+ "Enter the amount of numbers you would like to average");
// HERE!
AllNumbers = Double.parseDouble(ShowSome);
}//end while

您需要提示并更新 ShowSome

while (AllNumbers < 1)
{
// HERE!
ShowSome = JOptionPane.showInputDialog("You cannot enter a negative or a 0. "
+ " Enter the amount of numbers you would like to average");
// Get it again.
AllNumbers = Double.parseDouble(ShowSome);
}//end while

此外,Java 命名约定会以小写字母开头命名您的变量。使用 showSome 会更容易阅读 ShowSome 看起来像一个类名。与 allNumbers 相同。

关于java - 当用户输入 "0"时显示错误消息,无法退出 "error"消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25008214/

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