2016-06-15 100 views
0

我正在做一些基本的作业,而且它是我所知道的所有东西。但是我决定让它变得有点刺耳,而我错过的东西却引发了一个意想不到的错误。 这个想法是使用一个while循环,询问用户是否想要做某件事。只要他们说是,循环就会继续它所持有的操作(在这种情况下将十进制舍入为一个整数)。然而,只要我输入yes或其他任何值,循环就会在那里打破,并且不会继续到舍入部分。while bufferedInput change while while loop breaks

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!"); 
    } 
} 
+0

使用'等于()'比较字符串 – Ramanlfc

回答

0

使用.equals而不是==比较JAVA中的字符串。 试试这个:

contin.equals("yes") 
+0

好极了,我不知道我怎么错过了。对于我现在意识到的重复问题,我表示抱歉。它真的没有在我身上发现,那就是发生问题的字符串比较。 – Day64

+0

@ Day64:没问题。既然你是一个新手,它有点难以发现。但是在这里你应该使用你的调试技巧。首先,你应该试过在循环内部打印一些东西。你会看到它没有被打印。那么你应该试图在循环外打印出“==”。你会看到错误的。然后你会发现在比较字符串时存在一些问题,然后谷歌搜索会帮助你:) –