gpt4 book ai didi

java - 在 JAVA 中使用 while 循环询问用户输入

转载 作者:行者123 更新时间:2023-12-02 06:32:45 24 4
gpt4 key购买 nike

我花了大约 3 个小时来尝试解决这个简单的问题。这是我想要完成的任务:要求用户输入一个数字,然后添加这些数字。如果用户输入五个数字,那么我应该添加五个数字。

任何帮助将不胜感激。

  import java.util.Scanner;

public class loopingnumbersusingwhile
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);

int input;
System.out.println("How Many Numbers You Want To Enter");
total = kb.nextInt();
while(input <= kb.nextInt())
{
input++;

System.out.println("How Many Numbers You Want To Enter" + input);
int input = kb.nextInt();



}




}

}

最佳答案

您当前的代码尝试将 input 用于太多目的:当前输入的数字、输入的数字数量,并且还尝试将 total 用作输入的所有数字的总和以及要输入的数字数量。

您需要 4 个单独的变量来跟踪这 4 个单独的值:用户将输入多少个数字、到目前为止输入的数字、当前输入的数字以及总数。

int total = 0; // The sum of all the numbers
System.out.println("How Many Numbers You Want To Enter");
int count = kb.nextInt(); // The amount of numbers that will be entered
for(int entered = 0; entered < count; total++)
{
int input = kb.nextInt(); // the current number inputted
total += input; // add that number to the sum
}
System.out.println("Total: " + total); // print out the sum

关于java - 在 JAVA 中使用 while 循环询问用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935323/

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