Results 1 to 4 of 4
Thread: for loop help
- 09-23-2012, 07:15 PM #1
Student
- Join Date
- Aug 2012
- Posts
- 6
- Rep Power
- 0
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
My even and odd count don't show up right.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); } }
This is what my output would look like
What did I do wrong?Number 1: 2
Number 2: 8
2 8
total 35
even count 20
odd count 15
- 09-23-2012, 07:22 PM #2
Member
- Join Date
- Sep 2012
- Posts
- 26
- Rep Power
- 0
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.
- 09-23-2012, 07:26 PM #3
Student
- Join Date
- Aug 2012
- Posts
- 6
- Rep Power
- 0
Re: for loop help
Thanks. I found my error.
- 09-23-2012, 07:34 PM #4
Member
- Join Date
- Sep 2012
- Posts
- 26
- Rep Power
- 0
Similar Threads
-
Problem with while loop, assigning a variable with a different value every loop? Help
By JavaProg in forum New To JavaReplies: 2Last Post: 11-07-2011, 02:25 AM -
Is it Possible? Array elements Initialized in Loop, can it be viewed outside loop?
By JPH in forum New To JavaReplies: 1Last Post: 10-01-2011, 02:12 AM -
JTextField loop 2x for-loop WEIRD!
By Streetproject in forum AWT / SwingReplies: 2Last Post: 02-16-2011, 05:46 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks