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.

Member Avatar for ztini
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.

Member Avatar for ztini
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);
commented: helpful! :) +2
Member Avatar for ztini

Here you go.

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!

Member Avatar for ztini

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.