gpt4 book ai didi

java - 检查数组中的负数并重新提示输入正确

转载 作者:太空宇宙 更新时间:2023-11-04 13:09:53 27 4
gpt4 key购买 nike

这个想法是创建一周一天赚的钱的平均值,并且我的平均值必须用主方法中调用的方法来计算。这是简单的部分,但我坚持的部分是,如果输入小于零的数字,它应该给我一条错误消息并重新提示用户提供更好的值。我在这里寻找讲义并不是为了有人告诉我我做错了什么(如果它简单易行或指向正确方向的指针)。

import java.util.*;

public class weeklyAveragesClient2
{
public static void main(String [] args)//output averages in format
{
averageCash();
}

public static double averageCash()//use array and loop to calculate weekly average
{
double [] cashMoney;
cashMoney = new double[7];
Scanner scan = new Scanner(System.in);
int j = 0;
String s = "ERROR";

while (j < 7)
{
double num = cashMoney[j];

if (num == 0)
{
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
}
else if(num > 0)
{
System.out.print("Please enter an amount for day " + (j+1) +": ");
cashMoney[j] = scan.nextDouble();
j++;
}
else
{
System.out.println("Error: negative number please enter a number > 0");
}
}
System.out.println("Calculating...");

double sum = 0;
for (int i = 0; i < cashMoney.length; i++)
{
sum = sum + cashMoney[i];
}
double average = sum / (double)cashMoney.length;
System.out.println("Average: " + average);
return average;
}//end averageCash
}//end class

最佳答案

我添加了一些评论,希望能提供一些思考。

// This will *always* be zero at first because you haven't called scan.nextDouble() yet 
// and zero is the default value. So when you run the program, it will output "Error
// please enter a number > 0" before doing anything else
if (num == 0) {
System.out.println("Error please enter a number > 0");
num = j;
cashMoney[j] = scan.nextDouble();
} else if (num > 0) {
System.out.print("Please enter an amount for day " + (j + 1) + ": ");
cashMoney[j] = scan.nextDouble();
j++;
} else {
// If we get into this state, the user will never be invited to enter
// another number, since the last entered number was negative, so
// num == 0 is false, and
// num > 0 is false, so
// we'll end up back here. In fact, you'll enter an infinite loop and
// this message will be printed over and over again.
System.out.println("Error: negative number please enter a number > 0");
// cashMoney[j] = scan.nextDouble(); // <-- try prompting the user again
}

另请考虑正确缩进您的代码。它将大大增加可读性。如果您使用的是 Eclipse 等 IDE,则可以选择“源”>“格式”。

关于java - 检查数组中的负数并重新提示输入正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34078605/

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