Question

This is my first post and I have been searching google and stack overflow for the past 24 hours and can not seem to pin down my problem.

I am creating a simple square root program. For the input section I start a 'while' loop. I need it to compare two conditions. 1. is the input a number 2. is the input a number over ten.

I was successful in creating the original program, however I ran into a small problem while debugging. When I put in a vary large decimal or number I would get a run time error.

I discovered that I could use BigDecimal() to solve this problem.

However I am now running into a logic error that I cannot solve no matter how many times I search the internet.

The two conditions that I use in the while loop are:

    while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))

This will make sure that there is a BigDecimal, but will not make sure that the input number is over ten.

Here is the whole program

import java.math.BigDecimal;
import java.util.Scanner;

/**
 @author Mike
 */

public class SquareRootingWithoutBigDecimal 
{
public static void main( String [] args )
{
    Scanner scan = new Scanner(System.in);
    double inputNumber = 0.00;
    double rootedNumber = inputNumber;

     BigDecimal inputNumberBig = new BigDecimal(0.00);
     BigDecimal SENTINAL = new BigDecimal(10.00);
     String garbage;
     double garbageD = 0.00;


        System.out.println("Please Enter a number to be Square rooted"
            + "\nThe number must be 10 or greater ");       
        while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))
        {

        garbage = scan.nextLine();
        System.out.println("Please Enter a number to be Square rooted"
            + "\nThe number must be 10 or greater ");
        }

    inputNumberBig = scan.nextBigDecimal();
    inputNumber = inputNumberBig.doubleValue();  



    rootedNumber = inputNumber;
    do
    {
        rootedNumber = Math.sqrt(rootedNumber);
        System.out.println(rootedNumber);

    } while (rootedNumber >= 1.01 );

}

Any and all help is much appreciated.

-Mike

Était-ce utile?

La solution

inputNumberBig = scan.nextBigDecimal();
inputNumber = inputNumberBig.doubleValue();

These HAVE to go before you while loop for your logic to work.

Also,

while (!scan.hasNextBigDecimal() || (inputNumberBig.compareTo(SENTINAL)>0))

I could see this causing a problem. You should use && instead of ||

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top