在bufferedInput更改后循环中断

时间:2016-06-15 17:18:21

标签: java loops

我正在做一些基本的家庭作业,老实说我所知道的所有东西。但是我决定把它搞砸一下,而我失踪的东西却引发了一个意想不到的错误。 想法是使用while循环询问用户是否想要做某事。只要他们说是,循环就会继续它所持有的操作(在这种情况下将小数舍入为int)。但是,只要我输入yes或者其他任何内容,循环就会中断,并且不会继续进行舍入部分。

public class DecimalRounder {

   //Main class method that starts and ends the program. It is prepared to throw an IO exception if need be.
    public static void main(String args[])throws IOException
    {
        //Main initializes a new reader to take input from System.in
        InputStreamReader rawInput = new InputStreamReader(System.in);
        //Main then initializes a new buffer to buffer the input from System.in
        BufferedReader bufferedInput = new BufferedReader(rawInput);
        //Main initializes other used variable
        double castInput = 0.0;
        String contin = "yes";

        //Program then sets up loop to allow user to round numbers till content
        while (contin == "yes")
        {

            //Program asks user if they'd like to round.
            System.out.println("Would you like to round? Type yes to continue... ");

            contin = bufferedInput.readLine();
            //If user says yes, rounding begins. ERROR FOUND HERE?

            if (contin == "yes") //INPUT "yes" DOESN'T MATCH?
            {
                //Program then requests a decimal number
                System.out.println("Please enter a decimal number for rounding: ");
                String givenLine = bufferedInput.readLine();

                //rawInput is worked on using a try catch statement
                try {
                    //givenLine is first parsed from String into double.
                    castInput = Double.parseDouble(givenLine);
                    //castInput is then rounded and outputted to the console
                    System.out.println("Rounded number is... " + Math.round(castInput));
                    //Branch then ends restarting loop.
                }catch(Exception e){
                    //If the data entered cannot be cast into a double, an error is given
                     System.err.println("That is not a roundable number: " + e.getMessage());
                    //And branch ends restarting loop.
                }
            }
        }
        System.out.println("Have a nice day!");
    }
}

1 个答案:

答案 0 :(得分:0)

使用.equals代替==来比较JAVA中的字符串。 试试这个:

contin.equals("yes")