简体   繁体   中英

Range sum with a while loop for an assignment

I am new to Java and I'm trying to do a range sum with a while loop for an assignment. I need to use a while loop for this and the loop is not storing the total correctly and just adds the two values together.

public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in);
    System.out.println("Enter the first number: ");

    int first = keyboard.nextInt();
    System.out.println("Enter the second number: ");

    int second = keyboard.nextInt();
    if( second < first) {
        System.out.println("The sum is 0");
    }
    else if(second > first) {
        int total = 0;
        while (first < second) {
            total = second + first;
            second = second - 1;
            first = first +1;
            total = second + first;//this does not give the correct total 
        }
    System.out.print("The sum is "+total++);
    }
}

You are updating your total twice in the while loop, and you are changing both first and second variables in the loop. It would be clearer to modify just one of the numbers. I think a for loop is a little easier to read for a sum range. Here is an example of one that sums inclusive of both ends:

for (int i = first; i <= second; i++) {
  total += i;
}

here is a fix for your while loop (with it being inclusive of both first and second):

while (first <= second) {
  total += first;
  first++;
}

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