簡體   English   中英

在Java中將int作為輸入

[英]Taking int as input in java

我嘗試使用以下代碼讀取int輸入

import java.util.*;
public Add{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        ArrayList<Integer> arr = new ArrayList<>();
        while(scan.hasNextInt()){
            arr.add(scan.nextInt());
        }
        System.out.println(arr);
    }
}

當我用任何輸入運行程序時,請說-

1 2 4

直到我按CTRL+c才停止。 我還嘗試了其他一些變體(例如試圖將其讀取為String數組,但也沒有用),但是它們是相同的。問題是我不想提前給出輸入的大小。 如何從控制台輸入解析int?

您將需要檢查某些輸入並中斷循環,因為hasNextInt將等待鍵盤輸入。 您可以通過以下方法解決它:

int number;
while(scan.hasNextInt()){
    number = scan.nextInt();
    if (number == -1) {//if user types in -1, then you will come out of the loop.
        break;
    }
    arr.add(number);
}

由於您使用的是掃描儀,因此您可以嘗試以下技巧,而不是使用ArrayList

Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while (sc.hasNextInt()) {
 int num = sc.nextInt();
 System.out.println("Your entered number is: " + num);
}  

如果使用hasNextInt()則不必考慮數字解析。 不是整數的令牌將使您脫離循環。

暫無
暫無

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

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