Results 1 to 2 of 2
  1. #1
    SamJava_the_Hut is offline Senior Member
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    106
    Rep Power
    0

    Default Understanding the behavior of a switch statement structure without user input

    I'm going through an assessment in my book where one of the questions asks what the output of the following code would be:

    Java Code:
    package sam.main;
    
    public class Main{
    	
    	public static void main(String[] args) {		
    
    		int count = 0;
    		int x = 3;
    		while(count++ < 3) {
    			System.out.print("1 + (2 * " + count + ") divided by 3 has a remainder of ");
    			int y = (1 + 2 * count) % 3;//
    			System.out.println(y);
    			
    			switch(y) {
    			default:
    			case 0: x -= 1; break;
    			case 1: x += 5;
    			}
    		}
    		System.out.println(x);
    		
    	}//end of main method
    }
    The output of y, and the final value of x is easy enough to find out:

    Output:
    1 + (2 * 1) divided by 3 has a remainder of 0
    1 + (2 * 2) divided by 3 has a remainder of 2
    1 + (2 * 3) divided by 3 has a remainder of 1
    6


    Where I'm completely lost though is the switch statement structure on lines 14 thru 17. What is going on? How do I know which case will be chosen?

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,993
    Rep Power
    8

    Default Re: Understanding the behavior of a switch statement structure without user input

    The tricky part is probably the default case, which has no break, so it just falls over to the case 0: which substracts 1 from x.

    So:
    - x starts at 3
    - first run: y=0, case 0 is hit: x = 3-1 = 2
    - second run: y=2, no case, so the default is hit, but it has no break so it falls through to case 0: x = 2 - 1 = 1
    - third run: y=1, case 1 is hit: x = 1 + 5 = 6

    case 1 has no break either, but since it's the last case it doesn't really matter. Until the day you decide to add case 2, and then it will be broken (again). Make it a habit to end all cases with breaks (or returns).
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

Similar Threads

  1. Help with While Statement Structure
    By easyeatlanta in forum New To Java
    Replies: 7
    Last Post: 03-19-2013, 04:00 PM
  2. Replies: 3
    Last Post: 11-19-2012, 08:12 PM
  3. Replies: 2
    Last Post: 03-26-2012, 04:27 PM
  4. Confusing statement behavior / lib problem?
    By series0 in forum New To Java
    Replies: 3
    Last Post: 09-20-2010, 06:01 AM
  5. Can't get my "if" statement to read user input
    By daletron3030 in forum New To Java
    Replies: 7
    Last Post: 01-16-2009, 05:24 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •