使用Scanner类保存整数



我有一个关于Scanner类的快速问题。我有一个想法,制作一个简单的程序,开始计算我写的所有数字,但如果超过了极限,它应该停止。这不是问题。。。。

问题是,你写的第一个数字应该是告诉程序将要计数的数字。

举个例子。

当程序启动时,我会写下例如:

3
100
234
546

总计:880。

输出应该是100+234+546的总和。
开头的数字3只是告诉程序它应该读3个数字。我不明白如何使第一个数字成为告诉程序在开始计数之前应该输入多少个数字的数字。

如果您使用的是Java 8,您可以执行以下操作:

Scanner scan = new Scanner(System.in);
int N = scan.nextInt();  //First number is the count of numbers
//line below loops for you and sums at the end
int sum = IntStream.range(0, N).map(i -> scan.nextInt()).sum();

使用此代码

void yourMethod()
{
     int sum=0;
     Scanner scan = new Scanner(System.in);
     int conut=scan.next();
     for(int i=0;i<count;i++)
     {
       sum=sum+scan.next();
     }
 }

将第一个数字存储在一个名为counter或类似的变量中,然后执行一个循环(forwhilecounter次,在每次迭代中,您将读取下一个数字并求和。该算法似乎非常简单地从中创建代码。

怎么样:

Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
while(count>0){
   //your logic
   count--;
}

最新更新