计算总和及平均值u
代码如下:
package ClassDemo; import java.util.Scanner; public class ScannerTest {
public static void main(String[] args)
{
// scanerDemo01();
// scanerDemo02();
// scanerDemo03();
scannerDemo04();
}
private static void scanerDemo01() {
// 输入:123 abc
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
String str1 = scan.next();
System.out.println("输入的数据为:\n"+str1);
}
scan.close();
//输出:输入的数据为:123
}
private static void scanerDemo02() {
// 输入:123 abc
Scanner scaner = new Scanner(System.in);
if(scaner.hasNextLine()){
String str1 = scaner.nextLine();
System.out.println("输入的数据为:"+str1);
}
scaner.close();
//输出:输入的数据为:123 abc
}
private static void scanerDemo03() {
Scanner scaner = new Scanner(System.in);
if(scaner.hasNextInt()){
int intVar = scaner.nextInt();
System.out.println("输入的数据为:" + intVar);
}
scaner.close();
}
private static void scannerDemo04() {
Scanner scanner = new Scanner(System.in);
int numberOfInputs = 0;
double sumOfInputs = 0.0;
System.out.print("请输入一个数: ");
while (scanner.hasNextDouble()) {
// sumOfInputs = sumOfInputs + scanner.nextDouble();
sumOfInputs += scanner.nextDouble();
numberOfInputs++ ;
System.out.print("请输入一个数: ");
}
scanner.close();
if (numberOfInputs != 0) {
System.out.println("输入的数字的总和是: " + sumOfInputs);
System.out.println("输入的数字的平均数是: " + (sumOfInputs / numberOfInputs));
} else {
System.out.println("直接退出");
}
}
}