有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当我运行程序时,java循环重复两次

我是一个新的程序员,试图制作一个程序,添加所有用户输入的数字。代码如下:

import java.util.Scanner;
import java.io.*;
public class Adding
{
private int numOfInt, newInt;

/**
 * Constructor for objects of class Adding
 */
public Adding()
{
    // initialise instance variables
    Scanner console = new Scanner( System.in );
    System.out.print("How many integers will be added?");
    numOfInt = console.nextInt();
    newInt = 0;
}
public int addIntegers()
{
    int count = 0;
    int sum = 0;
    while( count <= numOfInt )
    {
        System.out.println("The count is: " + count + " and the current sum is: " + sum);
        count = count + 1;
        Scanner console = new Scanner( System.in );
        System.out.println("Enter an integer: ");
        newInt = console.nextInt();
        sum = sum + newInt;
    }
    return sum;
}
public void displaySum()
{
            System.out.println("the sum is " + this.addIntegers());
}
}

这是第二节课的主要内容:

import java.util.Scanner;
import java.io.*;
public class AddingMain
{
public static void main( String[] args )
{
   Adding add = new Adding();
   add.addIntegers();
   add.displaySum();
}
}

但是,循环重复两次(如下面的输入所示,经过编辑以节省空间),实际上忽略了输入的第一组数字:

How many integers will be added?3

The count is: 0 and the current sum is: 0

Enter an integer: 1

The count is: 1 and the current sum is: 1

Enter an integer: 2

The count is: 2 and the current sum is: 3

Enter an integer: 3

The count is: 3 and the current sum is: 6

Enter an integer: 1

The count is: 0 and the current sum is: 0

Enter an integer: 2

The count is: 1 and the current sum is: 2

Enter an integer: 3

The count is: 2 and the current sum is: 5

Enter an integer: 4

The count is: 3 and the current sum is: 9

Enter an integer: 5

the sum is 14

有人能解释为什么会发生这种情况以及如何解决它吗?谢谢大家!


共 (4) 个答案

  1. # 1 楼答案

     add.addIntegers(); // invoke 1st time
     add.displaySum();  // invoke 2nd time
    

    您显式调用了addIntegers()一次,第二次被displaySum()调用

    加法和显示和是两种不同的职责,你最好把它们分成两个函数。使displaySum()仅显示和,而不是添加整数。您可以在类Adding中创建一个实例变量sum,并将displaySum()更改为

    public int displaySum(){
        return sum;
    }
    
  2. # 2 楼答案

    您可以从main()中删除addInteger(),这样它只被调用一次,就可以得到所需的输出

  3. # 3 楼答案

    循环重复两次,因为您要调用addIntegers()两次

    你第一次通过写add.addIntegers();来调用addIntegers() 下次你通过写System.out.println("the sum is " + this.addIntegers());来调用addIntegers()

    this.addIntegers()再次调用方法addIntegers()

    Extra Suggestion

    您可以通过在类级别实例化scanner对象来使用scanner对象,也就是说,您不需要在代码中实例化scanner对象两次

    你可以这样

    public class Adding
    {
    private int numOfInt, newInt;
    Scanner console = new Scanner( System.in );
    
  4. # 4 楼答案

    原因是addIntegers被调用了两次,一次在main中调用,一次在displaySum中调用。因此,循环也会执行两次