【发布时间】:2011-09-28 21:15:50
【问题描述】:
我必须编写一个程序,使用嵌套循环来收集数据并计算几年内的平均降雨量。首先,程序应该询问年数。 (外循环将每年迭代一次。)内循环将迭代 12 次,每月一次。内部循环的每次迭代都会询问用户该月的降雨量。在所有迭代之后,程序应显示月数、总降雨量以及整个期间每月的平均降雨量。
输入验证:不接受小于 1 的数字作为年数。每月降雨量不接受负数。
我已经完成了程序,但是有一个小问题:当它要求输入英寸时,如果我输入 1 表示年份,它会要求我输入英寸 12 次。如果我先输入一个负数,它会告诉我该数字无效,然后再次循环并要求我输入一个等于或大于零的数字。现在,如果我输入一系列 >=0 的数字,然后输入一个负数,它并没有告诉我我不能输入一个负数。它根本不应该接受负数,但是当前 2 个或更多数字 >= 零时它会接受。
import java.util.Scanner;
public class Averagerainfallteller {
/**
* This program tells asks the user to enter an amount of years and then asks
* the user to given the amount of inches that fell for every month during
* those years and then give the average rain fall, total inches of rain and
* total months.
*/
public static void main(String[] args) {
double totalInches = 0;
double totalMonths = 0;
double avgInches = 0;
double inches = 0;
Scanner kb = new Scanner(System.in);
System.out.println(" PLease enter the number of years");
int numYears = kb.nextInt();
while (!(numYears >= 1)) {
System.out.println(" PLease enter the number that is more than or equal to one.");
numYears = kb.nextInt();
}
for (int years = 1; years <= numYears; years++) {
for (int months = 1; months <= 12; months++) {
System.out.println("How many inches fell for Year: " + years
+ ", during Month: " + months + "? ");
inches += kb.nextDouble();
while (!(inches >= 0)) {
System.out.println("PLease enter the number that is more than or equal to zero.");
System.out.println("How many inches fell for Year: " + years
+ ", during Month: " + months + "? ");
inches += kb.nextDouble();
}
}
}
totalMonths = 12 * numYears;
avgInches = totalInches / totalMonths;
System.out.println(".....HERE ARE THE RESULTS.....");
System.out.println("");
try {
Thread.currentThread().sleep(1000);
} catch (Exception e) {
}
System.out.println(" Total inches is " + totalInches);
System.out.println("");
try {
Thread.currentThread().sleep(1000);
} catch (Exception e) {
}
System.out.println(" Average Inches is " + avgInches);
System.out.println("");
try {
Thread.currentThread().sleep(1000);
} catch (Exception e) {
}
System.out.println(" Total months is " + totalMonths);
}
}
【问题讨论】:
-
哇。所有这些空白确实使它很难阅读。是否有机会重新格式化以使其更整洁、更易于阅读而无需滚动?
-
并删除那些什么都不做的尝试/捕获。只需在您的方法中声明
throws Exception。 -
自己整理了一下。
-
我是新来的 umm 如何删除空格?
标签: java