Hey for hw i gotta do a program that spits out the perfect squares between 0 and a number entered... well i got it done but it spits out 1 extra number that goes OVER what the person entered... here's my code.

public static void main(String[] args)
    {
        String userinput = JOptionPane.showInputDialog("Enter a positive integer");
        int j = Integer.parseInt(userinput);
        String space=" ";
        String num="";
        int b=0;
        for (int i =1; b < j; i++)
        {
            b = i * i;
            String numst = Integer.toString(b);
            num += " " + numst;
        }
        System.out.println(num + " are all the perfect squares between " + j);
    }

an example is i put i enter 26... it gives me "1 4 9 16 25 36" it should only give me up to 25... any insight would be appreciated.

System.out.println(num + " are all the perfect squares between " + j);

That is where the extra number comes from. Just change it to read:

System.out.println(" are all the perfect squares between " + j);

no i want it to list the perfect squares... which it does... but it lists 1 extra... for example i enter 26... it outputs 1 4 9 16 25 36.... all of those numbers are correct except the 36 should not be in there because 36 > 26.

Edited 5 Years Ago by eikal: n/a

int max = Integer.parseInt(JOptionPane.
        		showInputDialog("Enter a positive integer"));

        for (int i = 1, num = 1; Math.pow(i, 2) <= max; ++i) {
        	num = (int) Math.pow(i, 2);
        	System.out.print(num + " ");
        }
        
        System.out.print("are all the perfect squares between " + max);

Edited 5 Years Ago by ztini: n/a

Comments
helpful! :)

looking at your code i notice you incorporated the i*i and <= max into the for conditions, i think that is the reason why mine would produce the extra number. :) thanks!

Good observation. It was either do that or throw an if statement in there. This just seemed cleaner, imo.

This question has already been answered. Start a new discussion instead.