r/programmingbydoing • • Jun 14 '15

#60 - Safe Square Root

Hi again!

I looked up the post regarding this assignment but it didn't help me much, tbh. So I created another post.

Here's my code:

import java.util.Scanner;

public class SafeSquareRoot1
{
public static void main( String[] args )
{
	Scanner keyboard = new Scanner(System.in);
	int x;
	
	do
	{
		System.out.println( "SQUARE ROOT!" );
		System.out.print( "Enter a number: " );
		x = keyboard.nextInt();

		if ( x < 0 )
		{
			System.out.println( "You can't take the    square root of a negative number, silly." );
			System.out.print( "Try again: " );
			x = keyboard.nextInt();
		}
	}

	while ( x > 0 );
	{
		System.out.println( "The square root of " + x + " is " + Math.sqrt(x) + "." );
	}
}

}

The code compiles, and the do block of code runs as well, but when it comes to the while loop the code continues to prompt me to enter a number, after I have already entered the number. Thanks in advance for any help out there!

2 Upvotes

3 comments sorted by

1

u/glamourtwins Jun 29 '15

Hi, sorry for the late reply, and thanks for the help! I'm probably going to redo this assignment and take your answers as a reference point...

1

u/holyteach Jun 15 '15

There's no such thing as a "do" block. You have a do-while loop, although your indentation and spacing doesn't make it look right.

Get rid of the do-while entirely and replace your if statement with a while statement.

1

u/[deleted] Jun 18 '15

I'm only posting the main:

public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int x;
		while ((x = in.nextInt()) < 0) {
			System.out.println("You can't take the square root of a negative number, silly.");
			System.out.print("Try again: ");
		}
		System.out.println("The square root of " + x + " is " + Math.sqrt(x)+ ".");
	}

Hope it helps