简体   繁体   中英

Simple program using loops (Beginning Java)

I have to write a program using loops that calculates the sum of all odd numbers between a and b (inclusive), where a and b are inputs.

I made this (below) and it works fine, but I noticed one problem with it: when i enter a larger number followed by a smaller number for the inputs, it returns 0, but when i enter the smaller number first it works perfectly. Any quick fixes for this? :)

import java.util.Scanner;

public class ComputeSumAAndB
{

   public static void main (String[] args)
   {
       Scanner in = new Scanner(System.in); 
       System.out.print("Please enter 2 integers: "); //prompts user for ints
       int a = in.nextInt(); 
       int b = in.nextInt();
       int sum = 0;

       for (int j = a; j <= b; j++)
       {
           if (j % 2 == 1)
             sum += j;
       }
       System.out.println("The sum of all odd numbers (inclusive) between " + a + " and "+ b + " is " + sum);
   }
}
int temp;
if(a > b) {
    temp = a;
    a = b;
    b = temp;
}

Put this right before your for loop starts.


The if checks whether a (the first number entered) is larger than b . If it is, it swaps a and b . Now your for loop will always start with the smallest number and iterate up to the larger number (because after this if , a will always be the smaller number).

Using this method has the added side effect of making your output make sense. Your output will now always say: "between [smaller number] and [larger number]" .

rolfl's answer is more elegant and works perfectly fine, but when the user enters the larger number first, your output may look kind of weird: "between [larger number] and [smaller number]" , etc.

You can get the smaller and larger inputs by using the Math.min() and Math.max functions....

for (int j = Math.min(a,b); j <= Math.max(a,b); j++) {
    if (j % 2 == 1) {
        sum += j;
    }
}

It's not working because A is larger than B in the for loop, you have it iterate while A is less than or equal to B .

You could do what nhgrif says but it's changing your data.. But he is correct.

That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for , j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.

Actually you should do the following 2 things:

1 It is just just like rolfl mentioned above. You need to put the min and max in the right place in loop.

for (int j = Math.min(a,b); j <= Math.max(a,b); j++) {

if (j % 2 == 1) {
    sum += j;
}

}

2 Use if (j % 2 == 1) it is not enough to check whether the num is odd.

eg

a = -5 , b =0; What will be the result?

    int sum = 0;
    for(int j=-5;j<0;j++)
    {
        if(j%2 == 1)
        {
            sum+=j;
        }
    }

The value for sum will be 0.

We need to change the condition to if(!(j%2 == 0)) Then you will get the expected result.

That's because you are first expecting for the a input (inferior limit) and then the b (superior). When your program reaches the for, j = a so the condition a <= b is False, if the first input is larger. In other words it never enters the for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM