函数循环错误

时间:2017-12-02 13:31:13

标签: java loops for-loop

我尝试编写一个程序,它接受两个用户并计算它们之间的数字之和(加上它们自己的数字)。 但是我遇到了一个错误! 这是我的代码:

glDrawArrays:714: [MALI] glDrawArrays takes more than 5ms here. Total elapse time(us): 8248 

错误:

import java.util.Scanner;

public class ForLoop {

    public static void main(String[] args) {
        int sum =0;
        System.out.print("Enter first number: ");
        Scanner myScanner = new Scanner(System.in);
        boolean firsttest;
        if(firsttest = myScanner.hasNextInt()) {
            int firstNumber = myScanner.nextInt();
            System.out.print("Enter second number: ");
                boolean secondtest;
                if(secondtest = myScanner.hasNextInt()) {
                    int secondNumber = myScanner.nextInt();
                    for(firstNumber ; firstNumber <= secondNumber ; firstNumber++) {
                        sum = sum + firstNumber ;
                    }
                }else {
                    System.out.println("Second number is not correct format.");
                }
        }else {
            System.out.println("first number is not correct format.");
        }
            System.out.println("total= " + sum);
    }

}

2 个答案:

答案 0 :(得分:1)

更改

for(firstNumber ; firstNumber <= secondNumber ; firstNumber++)

for(; firstNumber <= secondNumber ; firstNumber++)

答案 1 :(得分:1)

这里不需要for循环的第一部分。该值已定义,并已初始化[02/Dec/2017:15:49:13 +0300] "POST /api/v1/user/register HTTP/1.1" 500 16904 "-" "GuzzleHttp/6.2.1 curl/7.55.0 PHP/7.1.9"

因此,你想要

int firstNumber = myScanner.nextInt();

看起来很奇怪,所以尝试一下while循环

for( ; firstNumber <= secondNumber ; firstNumber++) {
    sum = sum + firstNumber ;
}

此外,while(firstNumber <= secondNumber) { sum = sum + (firstNumber++); } 也适用