0

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.

Charles
  • 1,384
  • 11
  • 18
JamesB
  • 569
  • 1
  • 9
  • 31

3 Answers3

3

Write it as a for loop, with appropriate bounds (start at 4, since 4*4=16 > 15 and 3*3=9 < 15; finish at 14, since 14*14=196 < 200 and 15*15=225 > 200:

for (int i = 4; i <= 14; ++i) {
  System.out.println(i*i);
}

If you wanted to make the numbers 4 and 14 less "magical" with respect to your bounds of 15 and 200, you can write the loop thus:

for (int i = (int) Math.ceil(Math.sqrt(15)), squared;
     (squared = i * i) < 200; ++i) {
  System.out.println(squared);
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

If you wish to keep the while loop you can do this:

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


     void perfectSquareBetweenFifteenAndTwoHundred(){

          int i=4;
          int answer=0;

          while(answer<200){
                System.out.println(answer);
                answer = i*i;
                i++;
         }
     }
}

Here's how the code above works: Basically every iteration the answer printed out is the calculated from the previous iteration. To be honest this is the kind of code you should avoid writing as it relies on the state of the variable from the previous iteration and it isn't obvious how the code works at first glance.

fazed
  • 33
  • 5
1
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);
            }
        }
    }
}
Frank Neblung
  • 3,047
  • 17
  • 34