import java.util.Scanner;
public class AverageAndVariance {
public static void main (String[] args)
{
System.out.println("This program computes the average and variance of all numbers entered. ");
boolean finished = false;
double total = 0.0;
double average = 0.0;
double variance = 0.0;
Scanner inputScanner = new Scanner (System.in);
while (!finished)
{
System.out.println("Enter a number (or type 'exit'): ");
if (inputScanner.hasNextDouble())
{
total++;
double currentNum = inputScanner.nextDouble();
average = (average) + (currentNum - average) / total;
double prevAverage = ((average * total) - currentNum) / (total - 1);
if (total > 1)
{
double var1 = (variance * (total - 1));
double var2 = (currentNum - prevAverage) * (currentNum - average);
variance = (var1 + var2) / total;
}
System.out.println("So far the average is: " + average
+ "\nAnd the variance so far is: " + variance );
}
else if (inputScanner.hasNext("exit"))
{
finished = true;
System.out.println("Goodbye.");
inputScanner.close();
}
else
{
System.out.println("Invalid input.");
}
}
}
}
只是想知道如何在最后处理错误,我的else语句是一个无限循环?如何让它回到while循环的开头?我觉得我的程序效率很低。我遇到方差的问题但是当我把嵌套的if语句放入其中时呢?我怎样才能使我的代码更有效率?感谢。
修改 修复了无效的输入输出,只需将扫描仪放在while循环中,只是想知道这段代码是否比现在更有效? (即在保持相同功能的同时我可以删除任何if语句?)
答案 0 :(得分:0)
在上面的代码中它很好但 inputScanner.hasNextDouble()返回false我们输入错误的输入
import java.util.Scanner;
public class AverageAndVariance {
public static void main (String[] args)
{
System.out.println("This program computes the average and variance of all numbers entered. ");
boolean finished = false;
double total = 0.0;
double average = 0.0;
double variance = 0.0;
Scanner inputScanner = new Scanner (System.in);
while (!finished)
{
System.out.println("1. Enter a number ");
System.out.println("0. Exit ");
System.out.println("Enter Your Choice ");
try
{
int option= inputScanner.nextInt();
switch(option)
{
case 1:
total++;
System.out.println("Enter your Number");
double currentNum = inputScanner.nextDouble();
average = (average) + (currentNum - average) / total;
double prevAverage = ((average * total) - currentNum) / (total - 1);
if (total > 1)
{
double var1 = (variance * (total - 1));
double var2 = (currentNum - prevAverage) * (currentNum - average);
variance = (var1 + var2) / total;
}
System.out.println("So far the average is: " + average
+ "\nAnd the variance so far is: " + variance );
break;
case 0:
finished = true;
System.out.println("Goodbye.");
inputScanner.close();
break;
default:
System.out.println("Invalid Output");
break;
}
}
catch(Exception ex)
{
System.out.println("Error "+ex.getMessage());
finished = true;
}
}
}
}