W4 Homework Assignment

You will be required to demo your homework solutions during lab.

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 ) {

        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 );

    }

}

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.