gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:51:49 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

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

Extra Suggestion

您可以通过在类级别实例化 Scanner 对象来使用扫描仪对象,即您不需要在代码中实例化扫描仪对象两次。

你可以这样——

public class Adding
{
private int numOfInt, newInt;
Scanner console = new Scanner( System.in );

关于java - 当我运行程序时循环重复两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38806448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com