Results 1 to 4 of 4

Thread: for loop help

  1. #1
    kevintran is offline Student
    Join Date
    Aug 2012
    Posts
    6
    Rep Power
    0

    Default for loop help

    I am given this objective
    Lab Description : Run a loop from a provided start number to a provided stop number. Total up all numbers in the group, determine all odds in the group, and determine all evens in the group.




    Sample Data :
    1 5
    2 8
    5 15




    Sample Output :
    1 5
    total 15
    even count 2
    odd count 3

    2 8
    total 35
    even count 4
    odd count 3

    5 15
    total 110
    even count 5
    odd count 6

    This is my code
    Java Code:
    import java.util.*;
    
    public class lab08g {
    
    	public static void main(String[] args) {
    		Scanner input = new Scanner(System.in);
    		System.out.print("Number 1: ");
    		int num1 = input.nextInt();
    		System.out.print("Number 2: ");
    		int num2 = input.nextInt();
    		System.out.println(num1 + " " + num2);
    		int total = 0, even = 0, odd = 0;
    		for (int total1 = num1; total1 <= num2; total1++) {
    			total = total + total1;
    
    		}
    		System.out.println("total " + total);
    		for (int even1 = num1; even1 <= num2; even1++) 
    		{
    			if (even1 % 2.0 == 0) {
    				even = even + even1;
    			}
    		}
    		for (int odd1=num1;odd<=num2;odd1++)
    		{
    			if (odd1%2.0!=0)
    				odd=odd+odd1;
    		}
    
    
    			System.out.println("even count " + even);
    			System.out.println("odd count "+odd);
    
    
    	}
    }
    My even and odd count don't show up right.
    This is what my output would look like

    Number 1: 2
    Number 2: 8
    2 8
    total 35
    even count 20
    odd count 15
    What did I do wrong?

  2. #2
    JavaAdviser is offline Member
    Join Date
    Sep 2012
    Posts
    26
    Rep Power
    0

    Default Re: for loop help

    Take pen and paper and write down each value even and even1 and odd and odd1 respectively have at each iteration of the respective for loops.

    You should then be able to find the mistake yourself really soon.

  3. #3
    kevintran is offline Student
    Join Date
    Aug 2012
    Posts
    6
    Rep Power
    0

    Default Re: for loop help

    Thanks. I found my error.

  4. #4
    JavaAdviser is offline Member
    Join Date
    Sep 2012
    Posts
    26
    Rep Power
    0

    Default Re: for loop help

    Is your odd numbers count correct? I'm afraid there is another mistake in your for-loop for that.

Similar Threads

  1. Replies: 2
    Last Post: 11-07-2011, 02:25 AM
  2. Replies: 1
    Last Post: 10-01-2011, 02:12 AM
  3. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 05:46 PM

Posting Permissions

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