繁体   English   中英

多少个整数,整数的加法

[英]How many integers, addition of integers

import java.util.Scanner;
public class InputLoop
{
    public static void main(String[] args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter an integer to continue or a non integer to finish");

    while (scan.hasNextInt())
    {
        System.out.println("Enter an integer to continue or a non integer to finish");
        int value = scan.nextInt();
        System.out.print("user: ");
    }
    scan.next();
    {
        System.out.println ("You entered");
        System.out.println ();

    }
}

}

在它说“你输入”的地方,我必须输入有多少整数,例如“3”,然后将整数加在一起,例如“56”。 我不知道如何做到这一点,我该如何实施?

维护一个List<Integer>并在用户每次输入整数时添加到此列表中。 因此,添加的整数数量将只是list.size() 对于您当前所做的事情,无法访问用户的旧输入。

您也可以使用存储总数和计数的变量(在这种情况下可以正常工作),但在我看来,如果您决定更新/修改此代码,使用List方法将为您提供更大的灵活性,这是某事作为程序员,您应该牢记这一点。

List<Integer> inputs = new ArrayList<Integer>();

while (scan.hasNextInt()) {
    ...
    inputs.add(scan.nextInt());
}

...

只需保留一个名为count的变量和一个名为sum的变量。 并将while循环中的代码更改为:

 int value = scan.nextInt();
 sum += value;
 count++;

最后,您可以在while循环结束后输出两者。

顺便说一句,您不需要在scan.next()之后放置那些花括号 { } ; 它们是不相关的,并且总是独立于scan.next()执行;

所以只需将其更改为:

scan.next();  //I presume you want this to clear the rest of the buffer?
System.out.println("You entered " + count + " numbers");
System.out.println("The total is " + sum);

有一个 count 变量,在main的开头声明并递增它。

您还可以以相同的方式维护 sum 变量。

while (scan.hasNextInt())
{
    System.out.println("Enter an integer to continue or a non integer to finish");
    int value = scan.nextInt();
    count++;
    sum += value;
    System.out.print("user: ");
}

scan.next();
{
    System.out.println ("You entered");
    System.out.println (count);
}

对于您想要输出的内容,您不需要保留用户输入的历史记录。 您只需要一个运行总数和一个计数。 您也不需要最后一次调用scan.next()或将最后一次println调用包含在单独的块中。

public class InputLoop
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter an integer to continue or a non integer to finish");

        int total = 0;
        int count = 0;
        while (scan.hasNextInt())
        {
            System.out.println("Enter an integer to continue or a non integer to finish");
            int value = scan.nextInt();
            total += value;
            ++count;
            System.out.print("user: ");
        }
        System.out.println ("You entered " + count + " values with a total of " + total);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM