Hi :) I am trying to make a program that will find the first x perfect squares. I have done and redone this many times, but it never works. So basically, it needs to do two things: check if y is a perfect square. If it is, it needs to check if this number is a magic square.
A magic square is a perfect square where you can do 1+2+3+4 and so on, and end up with a perfect square. This for my AP comp sci class, and the full assignment is here:
http://www.howard.k12.md.us/rhhs/helloworld/LessonA12/Lab-A12-1.html
import java.util.Scanner;
public class FunLoops {import java.util.Scanner;
public class FunLoops {
int x;
int a = 0;
double b = 1;
int incrementer = 0;
int total = 0;
Scanner in;
public FunLoops(){
in = new Scanner(System.in);
loops();
}
public void loops(){
System.out.println("How many magic squares do you want?");
int input = in.nextInt();
for(double x = Math.pow(b, 2); a < input; b++){ //x will only be a perfect square
while(true){
if (total == x){ // total is the result of 1+2+3.... If total = x, the perfect square is a magic square.
System.out.print(x + ", "); // prints all magic squares
a++; // stops "for" loop when it has reached input.
break; //breaks "while" loop to start over with next perfect square, after printing magic square.
}
else{
incrementer += 1; // 1+2+3....
total += incrementer; // .... = ?
if (total / 2.0 > x){ // if the perfect square isn't a magic square, after testing, total/2 > x (x is the perfect square)
break; // ....and it will stop the "while" loop, in order to try next perfect square
}
}
}
}
}
}
Main:
public class FunLoopsTester {
public static void main(String[] args) {
FunLoops app = new FunLoops();
}
}
Right now, the code prints "1" (which is in fact a magic square) "input" times. (if the input is 4, it will print "1" four times.)
I really appreciate all help I can get. I added a lot of comments to make it easier for you to follow.