Search code examples
javalogicrecompile

More Expressive Code


Is there a more intelligent way to write this code avoiding the repetition of the condition (answer<200) in the WHILE and in the IF?

 public class HelloWorld
{
  public static void main(String[] args)
  {
  perfectSquareBetweenFifteenAndTwoHundred();
  }
 }

 void perfectSquareBetweenFifteenAndTwoHundred(){

   int i=1;
   int answer=0;

    while(answer<200)
    {
      answer = i*i;

         if(answer>15 && answer<200)
         {
         System.out.println(i*i);
         }

      i++;
    }
 }
}

Thanks.


Solution

  • public class MyClass {
        public static void main(String[] args) {
            for (int i = 1; true; i++) {
                int square = i * i;
                if (square > 200) {
                    return;
                }
                if (square > 15) {
                    System.out.println(square);
                }
            }
        }
    }