switch statement

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sugard
    New Member
    • Aug 2007
    • 50

    #1

    switch statement

    my task is to create a set of 100 random numbers between -20 and 20. Thereafter i need to count the number of -20, -10, 0 10 and 20 by using a switch statement.

    Following is my code:
    Code:
    			int rnd2=0;
    						{
    							for (int x=1 ; x<=100 ; x++)
    
    
    								{
    								rnd2 = randInt(-20,+20);
    								System.out.println(x+ "=>"+rnd2);
    
    
    								}
    
    
    		//================ Listing The occurencies of the selected numbers here below===============//
    
    					int No1=0;
    					int No2=0;
    					int No3=0;
    					int No4=0;
    					int No5=0;
    
    
    					switch (rnd2)
    
    
    					{
    
    
    
    					case -20:
    									No1 = No1 +1;
    									break;
    
    					case -10:		No2 ++;
    									break;
    
    					case   0:
    									No3 ++;
    									break;
    
    					case  10:
    									No4 ++;
    									break;
    
    					case  20:
    									No5 ++;
    									break;
    					}
    
    
    
    				System.out.println("\n\n-20=> " +No1);
    				System.out.println("-10=> " +No2);
    				System.out.println(" 0=> "  +No3);
    				System.out.println(" 10=> " +No4);
    				System.out.println(" 20=> " +No5);
    		}
    Though, the problem is that when i am compiling it, it is always being displayed that the number of occurance is 0. Can please some1 help me of where the error is??

    thanks very much
  • sicarie
    Recognized Expert Specialist
    • Nov 2006
    • 4677

    #2
    Originally posted by sugard
    Though, the problem is that when i am compiling it, it is always being displayed that the number of occurance is 0. Can please some1 help me of where the error is??
    Yep, right here:
    [code=java]
    int rnd2=0;
    {
    for (int x=1 ; x<=100 ; x++)
    {
    rnd2 = randInt(-20,+20);
    System.out.prin tln(x+ "=>"+rnd2);
    }

    //case statement below

    [/code]

    So let me ask you - what does rnd2 contain after the for loop completes? If you said 100 values, you'd be wrong. I'm betting you also don't have the seed value changing every time, so you're always ending up with the same number at the end, and that number is not -20, 0, 20, etc...

    Comment

    Working...