簡體   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