嗨我有麻烦的家庭作业。该程序使用两种不同的方法来平均和显示用户定义的一组数字。我想到了所有这些,但是我在检查错误时遇到了困难。我不希望用户能够说,他们想要在开始时平均负数或零数量的数字,所以我试图使用if/else语句和do while循环来向用户显示错误消息并让他们有机会再次尝试。使用do/while循环错误检查用户输入
当用户输入1以在输入无效数字后再次尝试该程序时,程序允许用户再次尝试。但是,一旦他们正确地输入了所有内容并完成程序,程序就会重新开始。一旦程序正确完成,我希望程序结束。
任何帮助,将不胜感激。谢谢!
public static void main(String[] args)
{
//Defining the variables in main method
int inputNumber;
int repeat = 0;
//Creating the array and checking for negative or no numbers using do..while and if..else
do
{
String aStr = JOptionPane.showInputDialog(null, "How many numbers would you like to be averaged?");
inputNumber = Integer.parseInt(aStr);
if(inputNumber <= 0)
{
String errorStr = JOptionPane.showInputDialog(null, "Cannot be a negative number or a zero. Press 1 to try again.");
repeat = Integer.parseInt(errorStr);
}
else
{
double[] array = new double[inputNumber];
displayAverage(average(array));
}
} while (repeat == 1);
} // end main
// Creating a method called "average" that calculates and returns the average to main
public static double average(double [] methodArray)
{
// Defining variables in average method
int index;
double total = 0;
double average;
// Taking user inputed numbers and adding them up
for(index = 0; index < methodArray.length; index++)
{
String bStr = JOptionPane.showInputDialog(null, "Enter number " + (index + 1));
methodArray[index] = Double.parseDouble(bStr);
total = total + methodArray[index];
}
// Calculating the average
average = total/index;
return average;
} //end average method
// Creating a method called "displayAverage" that displays the average in a dialog box
public static void displayAverage(double returnedAverage)
{
JOptionPane.showMessageDialog(null, "The average of all your numbers is " + returnedAverage);
}
} //结束类
究竟是什么问题?你无法理解“do-while”的含义?或者你在检查输入的有效性方面有问题?或者你有超过1个输入的问题? – 2014-11-24 01:51:41
我遇到的问题是与输入的有效性检查有关。我似乎要么不正确地使用do-while要么从某些答案/评论的外观来看它位于不正确的位置。 – detomaso55 2014-11-24 03:23:44
下次如果你可以写下一个只显示问题的小程序(calculateAverage和displayAverage简直不相关),那么它会好得多,并且2.明确你遇到的预期行为和有问题的行为。在很多情况下,通过做1,你可以自己找出解决方案。 – 2014-11-24 03:29:36