java - 提示用户输入两个数,并输出这两个数的平均值(若输入个数或格式有误,提示用户输入错误),使用try,catch,finally报错
阿神
阿神 2017-04-18 10:43:47
0
2
713
阿神
阿神

闭关修行中......

Antworte allen(2)
Peter_Zhu
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws IOException {
        Test t = new Test();
        t.waitInput();
        System.out.println("Average Value:" + t.average());
    }

    private double num1;
    private double num2;

    public void waitInput() throws IOException {
        while (true) {
            System.out.printf("Please enter two numbers:(Separated by spaces)\n");
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = reader.readLine();
            String[] parts = line.trim().split("\\s+");

            if (parts.length < 2) {
                System.out.println("ERROR: incorrect input");
                continue;
            }

            try {
                num1 = Double.parseDouble(parts[0]);
                num2 = Double.parseDouble(parts[1]);
                break;
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }

    public double average() throws IOException {
        return (num1 + num2) / 2;
    }
}
左手右手慢动作

每次while循环就生成一个BufferedReader对象,而且不关闭?

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage