Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于java中的Scanner类,当用于计数时会提供错误的结果_Java - Fatal编程技术网

关于java中的Scanner类,当用于计数时会提供错误的结果

关于java中的Scanner类,当用于计数时会提供错误的结果,java,Java,但得到的答案是-2147450875。请告诉我原因?您必须将总和存储到不同的变量中,否则它将成为一个无终止的无限循环 由于Integer类具有循环属性,因此在2147483647语句a=a+i之后使其成为负数,for循环检查将中断循环,即i(零)

但得到的答案是-2147450875。请告诉我原因?

您必须将总和存储到不同的变量中,否则它将成为一个无终止的无限循环

由于Integer类具有循环属性,因此在
2147483647
语句
a=a+i之后
使其成为负数,for循环检查将中断循环,即
i(零)

publicstaticvoidmain(字符串[]args){
扫描仪=新的扫描仪(System.in);
System.out.println(“输入一个数字”);
整数a=scanner.nextInt();
整数和=0;
System.out.println(“a的值”+a);
对于(整数i=0;i
>这是代码。当代码被执行时,我希望计数像a=a+ia=5+1A=6+2A=7+3。。。。但得到的答案是-2147450875。请告诉我为什么?您的输入是什么?对于代码,我在scanner类中给出的输入是5P.S。检查如何调试。调试教程,如step-into-step-out(为google添加了足够的术语),将有助于比Stackoverflow.P.S.更快地解决这些问题。循环实际停止的原因是由于int值的限制,一旦你越过2^32-1,
a
的值变为负值,导致循环停止。
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("input a number");
    Integer a = scanner.nextInt();
    System.out.println("value of a "+ a);

    for(Integer i = 0 ; i < a; i++){
        a = a + i;
        System.out.println("for loop :"+ a);
    }
    System.out.println("value of a "+a);
    scanner.close();
}
a = a + i 
a = 5 + 1 
a = 6 + 2 
a = 7 + 3 
.... 
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("input a number");
    Integer a = scanner.nextInt();
    Integer sum = 0;
    System.out.println("value of a "+ a);

    for(Integer i = 0 ; i < a; i++){
        sum = sum + i;
        System.out.println("for loop :"+ sum);
    }
    System.out.println("value of sum "+sum);
    scanner.close();
}