Skip to content

Instantly share code, notes, and snippets.

@witchica
Created October 25, 2018 08:57
Show Gist options
  • Save witchica/d15fe7eaca569fada8d34cadb78f5d7f to your computer and use it in GitHub Desktop.
Save witchica/d15fe7eaca569fada8d34cadb78f5d7f to your computer and use it in GitHub Desktop.
package sqrt;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
public class SquareRoot
{
private static NumberFormat formatter = new DecimalFormat("#0.00");
public static void main(String[] args)
{
/* Initialize variables and open scanner */
Scanner scanner = new Scanner(System.in);
/* Loop until the application is closed */
while(true)
{
//Get input from the user
System.out.print("Please enter a number: ");
String input = scanner.nextLine();
try
{
//Parse input to a double and get the square root
double numberInput = Double.parseDouble(input);
double squareRoot = Math.sqrt(numberInput);
//Format the numbers for output
String numberInputString = parseDoubleForOutput(numberInput);
String squareRootString = parseDoubleForOutput(squareRoot);
//Output to the user
System.out.println(String.format("The square root of %s is %s", numberInputString, squareRootString));
}
catch(Exception e)
{
//Inform the user of an error
System.out.println("Please enter a valid number");
}
//Ask the user if they want to continue using the application and gather their input
System.out.print("Do you want to continue using the application (Y/N)?: ");
String finalInput = scanner.nextLine().toLowerCase();
//If the input is n (or no) then exit the application and close the scanner gracefully
if(finalInput.startsWith("n"))
{
System.out.println("Thanks for using the application!");
scanner.close();
System.exit(0);
}
else
{
//Otherwise continue
continue;
}
}
}
/*
* This function takes a double and formats it for output taking into account large numbers which
* may have issues displaying normally (if the number contains E that number is simply output without formatting)
*/
private static String parseDoubleForOutput(double d)
{
if(String.valueOf(d).contains("E"))
{
return String.valueOf(d);
}
else
{
return formatter.format(d);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment