簡體   English   中英

如何使用for循環輸入10個數字並僅打印正數?

[英]How to use for loop to input 10 numbers and print only the positives?

我試圖做一個“ for”循環,要求用戶輸入10個數字,然后只打印正數。

無法控制輸入量。 我不斷獲得無限的輸入,直到我添加一個負數。

import java.util.Scanner;

public class ej1 {
    public static void main(String args[]) {

        int x;

        for (x = 1; x >= 0; ) {
            Scanner input = new Scanner(System.in);
            System.out.print("Type a number: ");
            x = input.nextInt();
        }
    }
}

從語法的角度來看,此代碼存在一些問題。

  • for (x = 1; x >= 0; )的語句將始終循環,因為x始終大於0,特別是因為您沒有引入任何使xx的條件。

  • 您要一遍又一遍地聲明掃描儀。 您只應在循環外部聲明一次。 您可以根據需要多次重復使用它。

  • 您將要nextInt()之后使用nextLine()以避免掃描儀出現一些奇怪的問題。

    另外,您可以使用nextLine()並使用Integer.parseInt解析該行。

也就是說,有幾種方法可以控制此情況。 使用for循環是一種方法,但是如果要確保僅打印出十個正數,而不管輸入了多少個負數,事情就會變得很棘手。 這樣,我建議改為使用while循環:

int i = 0;
Scanner scanner = new Scanner(System.in);
while(i < 10) {
    System.out.print("Enter a value: ");
    int value = scanner.nextInt();
    scanner.nextLine();
    if (value > 0) {
        System.out.println("\nPositive value: " + value);
        i++;
    }
}

如果需要輸入十個值,則將增量語句移至if語句之外。

i++;
if (value > 0) {
    System.out.println("\nPositive value: " + value);
}

提示:如果您想存儲正值以供以后參考,則必須使用某種數據結構將其保存在其中-就像數組一樣。

int[] positiveValues = new int[10];

如果讀入的值是正數,則只將值添加到該特定數組中,並且可以一次將它們打印在最后:

// at the top, import java.util.Arrays
System.out.println(Arrays.toString(positiveValues));

...或循環播放:

for(int i = 0; i < positiveValues.length; i++) {
    System.out.println(positiveValues[i]);
}
Scanner scan = new Scanner(System.in);
int input=-1;
for(int i=0;i<10;i++)
{
 input = sc.nextInt();
if(input>0)
System.out.println(input);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM