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

774 Views Asked by At

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); 

        }
    }
}
3

There are 3 best solutions below

0
Robert Bain On BEST ANSWER

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:");
    }
}
2
Rahul Singh On

As mentioned by Elliott in the comment, the loop is never entered. Reason: a1 is assigned the value of a and then you are checking if a1. Which is not true and hence the for-loop is terminated even before its 1st iteration. For what you are trying to achive, use:

for (a1=a; a1 >= 0; a1--) {
    if (Math.floor(a1)==0)
    System.out.println("The largest square has side length" + a1); 
}
2
ManLaw On

If I understand your problem correctly, I think you want to make a1 decrease in value until it reaches 0. Maybe you need

for ( a1=a; a1 >= 0; a1--) {
        if (Math.floor(a1)==0)
        System.out.println("The largest square has side length" + a1); 
 }

UPDATE EDIT: Removed declaration int from a1 inside the loop because it was likely the source of the other bug ( double declaration of a1).