W7 Homework Assignment

1) This problem is essentially the last question from the previous quiz, which many did not get right. Consider the following program, which uses if/else-if/else to perform decision-making:
 

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
    int x = stringReader.nextInt(); // convert the user inputString to an int(if possible)

    int y;
    if( x == 0 ) { // x is 0
        y = -1;
        System.out.println("x=0 and y=-1");
    } else if( x==1 || x==2 ) { // x is 1 or 2
        y = 0;
        System.out.println("x=1 or 2 and y=0");
    } else { // x is any other value
        y = 1;
        System.out.println("x is some other value and y=1");
    }
}
Your assignment is to first create a program containing the above main() method. Run it and observe its output for various values of x.

Next, convert the decision logic using if/else-if/else to use a switch statement instead. Be sure to use break and default in your solution appropriately. Run the modified program to make sure it behaves as expected. This is the code you should submit as your homework solution.

As an investigation, comment out the break statements and run the program again for various values of x. What changes do you observe? Explain in comments at the bottom of your program.

 

 

2) For the BankAccount class we discussed in lecture, implement a method that generates a mini-statement similar to the following:

"Statement for account 123-345:
Balance is $123.45"

The method signature of the method should be as follows: public String getMiniStatement()