为什么使用double作为输入总是返回0作为结果?

时间:2015-10-19 21:16:54

标签: java bufferedreader

我正试图解决这个“错误”:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PassingVariables {

    double answer, myNumber1, myNumber2; 

    public static void main (String[] args) throws Exception {
        new PassingVariables();
    }

    public PassingVariables() {
        InputValue1();
        InputValue2();
        calc((double) myNumber1, (double) myNumber2);
    }

    public void InputValue1() {
        BufferedReader input1 = new BufferedReader (new     InputStreamReader(System.in));
        try {
            System.out.println("Type in a number: ");
            myNumber1 = Integer.parseInt(input1.readLine());
        } catch (Exception e){} 
    }

    public void InputValue2() {
        BufferedReader input2 = new BufferedReader (new InputStreamReader  (System.in));
        try {
            System.out.println("Type in another number");
            myNumber2 = Integer.parseInt(input2.readLine());
        } catch (Exception e){}
    }

    public double calc(double myNumber1, double myNumber2){
        double answer = ((double)myNumber1 + (double)myNumber2);
        System.out.println("Your number is: " + (double) answer);
        return answer;
    }
}
事情是:这段代码没有给我回复双打结果,这正是我想要的。 每次我放一个双,它给我的结果是值0.0 但我尝试使用整数,它给了我一些像

的结果

1 + 3 = 4.0

1 个答案:

答案 0 :(得分:1)

因为您正在使用Integer.parseInt(input2.readLine());尝试将parseInt行更改为Double.parseDouble(...)

修改

这里是更新的代码

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PassingVariables {

    double answer, myNumber1, myNumber2; 

    public static void main (String[] args) throws Exception {
        new PassingVariables();
    }

    public PassingVariables() {
        InputValue1();
        InputValue2();
        calc((double) myNumber1, (double) myNumber2);
    }

    public void InputValue1() {
        BufferedReader input1 = new BufferedReader (new     InputStreamReader(System.in));
        try {
            System.out.println("Type in a number: ");
            myNumber1 = Double.parseDouble(input1.readLine());
        } catch (Exception e){} 
    }

    public void InputValue2() {
        BufferedReader input2 = new BufferedReader (new InputStreamReader  (System.in));
        try {
            System.out.println("Type in another number");
            myNumber2 = Double.parseDouble(input2.readLine());
        } catch (Exception e){}
    }

    public double calc(double myNumber1, double myNumber2){
        double answer = ((double)myNumber1 + (double)myNumber2);
        System.out.println("Your number is: " + (double) answer);
        return answer;
    }
}