大家好,我是新手。我正在为我的编程部门做任务,所以请耐心等待。
所以我要做的就是编写一个可以输入人的年龄的代码,从1到120之间的整数。然后用户必须计算平均年龄,并且应该计算为实数。但是用户必须输入年龄值,直到用户输入0,即停止程序然后输出平均值。如果用户输入的年龄无效,则程序应继续重新提示用户,直到他们进入有效年龄。
所以我尽了自己的责任。我创建了一个代码,我想出了这个:
public static void main(String[] args)
{
int ageValue = 0;
double getAge;
getAge = inputAge();
System.out.println("Average age is: " + getAge);
}
public static double inputAge()
{
int ageValue = 0;
double avgAge = 0;
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 120; i++)
{
System.out.println("Enter age");
ageValue += sc.nextInt();
avgAge = ageValue / (double) i;
if (ageValue == 0)
{
System.out.println("Average age is: " + avgAge);
System.exit(0);
}
while (ageValue < 0 || ageValue > 120)
{
System.out.println("Invalid input. Try again!");
ageValue = sc.nextInt();
}
}
return avgAge;
}
现在我放下了我的代码,我的平均配方以某种方式工作。现在,问题是,当我按0时,它不会提示&#34;如果&#34;声明。但是,当第一个&#34;输入你的年龄&#34;提示出现,我按0,&#34;如果&#34;声明有效。但是对于每次迭代,程序都不允许我执行该语句。
另一方面,我也在努力弄清楚如何在不使用break或System.exit()的情况下退出循环,因为这会给我零标记。我想要的是当我按0时,它应该退出循环并输出平均值,就像任务所说的那样。
我不知道你们是否可以得到它..代码是否合适?我是在正确的轨道上吗?我错过了什么吗?
干杯
答案 0 :(得分:1)
您可以考虑使用do while
循环方法。这将允许您的代码自然运行一次,并在用户输入0
后退出:
int ageValue = 0, numOfAges = 0, sumOfAges = 0;
do {
System.out.println("Enter age");
ageValue = sc.nextInt();
if (ageValue < 0 || ageValue > 120)
System.out.println("Bad value... try again");
else if (ageValue != 0) {
sumOfAges += ageValue;
numOfAges++;
}
} while (ageValue != 0);
return ((double)sumOfAges / numOfAges);
答案 1 :(得分:0)
另一方面,我也在努力弄清楚如何在不使用break或System.exit()的情况下退出循环,因为这样会给我零标记。
你可以在for循环中使用另一个条件
boolean finished = false;
for (int i = 1; i <= 120 && finished == false; i++)
并替换
System.exit(0)
与
finished = true;
但是,我会质疑为什么使用&#34; break&#34;会给你零分。这正是针对的场景。
答案 2 :(得分:0)
你可以尝试这种方法。
我已经纠正了退出条件以及平均完成的方式。
你在代码中显示的“for”循环将样本数限制为120,但问题并没有这样说,所以我冒昧地将你的问题推广到任意数量的样本。
首先,您应该查找“if-else”条件结构,因为这是您的代码中缺少的主要内容。
https://en.wikipedia.org/wiki/Conditional_(computer_programming)
您可以将问题的表达方式表达为:
当输入绑定[1,119]内的任何值时,将值添加到系列并重新计算平均值
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Final Average age is: "+inputAge());
}
private static double inputAge()
{
int ageValue=0;
double avgAge=0;
boolean shouldExit=false;
Scanner sc=new Scanner(System.in);
List<Integer> samples=new ArrayList<Integer>();
// loop until flag is true
while(!shouldExit)
{
System.out.println("Enter age");
ageValue=sc.nextInt();
if(ageValue==0)
{
shouldExit=true;
}
else if(ageValue<0||ageValue>120)
{
System.out.println("Invalid input. Try again!");
}
else
{
// add current input in the samples and calculate average over all the samples
samples.add(ageValue);
avgAge=getAvg(samples);
System.out.println("Current Average age is: "+avgAge);
}
}
sc.close();
return avgAge;
}
private static double getAvg(List<Integer> samples)
{
double avgAge=0;
for(Integer tmp:samples)
{
avgAge+=tmp;
}
return avgAge/(double) samples.size();
}
}