W4 Homework Solution

1) Complete the main() method of the program we started in class, adding an else block so that when the user enters a negative number, an error message is generated.


public static void main(String[] args) {

    String inputValue = JOptionPane.showInputDialog("Enter a value:");

    Scanner stringReader = new Scanner( inputValue ); // create a Scanner that can convert Strings to numeric values

    double value = stringReader.nextDouble(); // convert the user inputString to a double (if possible)

    System.out.println("The value is " + value );

    if( value >= 0 ) { // 0 or positive value

        value = Math.sqrt( value ); // compute the square root of the value and reassign the result to the same variable

        System.out.println("The square root of the value is " + value );

    } else { // value is negative - Note we could also write else if( value < 0 )
        System.out.println("Can't take the square root of a negative number!");
    }

}

2) Write another program that prompts the user to enter a positive integer value from 5 to 9. Use nested if conditionals to:

  1.     Compute and print the square of the value, only if the entered value is in the range 5 through 9.
  2.     Print an error message stating that the number was too large if it was greater than 9.
  3.     Print a different error message stating that the value is too small if it was less than 5 but greater than 0.
  4.     Otherwise, print an error message stating that the value was 0 or negative.
public static void main(String[] args) {

    String inputValue = JOptionPane.showInputDialog("Enter a value from 5 to 9:");

    Scanner stringReader = new Scanner( inputValue ); // create a Scanner that can convert Strings to numeric values

    int value = stringReader.nextInt(); // convert the user inputString to a int (if possible)

    System.out.println("The value is " + value );

    if( value > 9 ) { // too large

        System.out.println("Error. The value is too large (greater than 9)." );

    } else if( value < 5 ) { // too small

        // use a nested-if to determine the remaining condition
        if( value > 0 ) { // still greater than 0
           System.out.println("Error. the value is smaller too small (less than 5)." );
        } else {  // less than or equal to 0
           System.out.println("Error. the value is negative" );
        } 

    }

}