Search code examples
javafor-loopperfect-square

How do I find the closest perfect square less than the input, or the perfect square can be the input


I want to make a program that gets a number input and finds the closest perfect square to determine the square length. Thus, the closest perfect square has to be less than the input. For example, if the input is 8, the largest side length of the square is 2. The problem is that the program will ask me to input a number but does not output anything after that. It also says I have a duplicate local variable a1.

import java.util.Scanner;  
public class J1 {

    public static void main(String[] args) {

        int a;
        int a1;

        Scanner number = new Scanner(System.in);
        System.out.println("Number: ");
        a = number.nextInt(); 
        int n = (int) Math.sqrt(a1); 

        /* remove int from a1 */
        for ( int a1=a; a1<a; a1--) {

            if (Math.floor(a1)==0)
            System.out.println("The largest square has side length" + a1); 

        }
    }
}

Solution

  • There are various problems with the code that others have pointed out and I'm sure you'll take them on board. To solve your problem though, I'd do something like this. The while loop lets you keep trying new values until you enter -1.

    public static void main(String[] args) {
        System.out.println("Enter value:");
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            boolean hasPerfectSquare = false;
            int input = sc.nextInt();
            if (input == -1) {
                break;
            }
            for (int i = input; i > 0; i--) {
                if (Math.floor(Math.sqrt(i)) == Math.sqrt(i)) {
                    hasPerfectSquare = true;
                    System.out.println((int) Math.sqrt(i));
                    break;
                }
            }
            if (!hasPerfectSquare) {
                System.out.println("No perfect square");
            }
            System.out.println("Enter value:");
        }
    }