簡體   English   中英

Java Scanner.nextInt() 跳過輸入

[英]Java Scanner .nextInt() skipping inputs

Java 新手這里,嘗試通過下面表格的輸入進行掃描:

3

3 3
101
000
101

1 2
11

5 5
10001
00000
00000
00000
10001

(第一個數字是測試用例的個數,然后是行和列,0s和1s是世界的state,以此類推。基本上和任何典型的BFS問題一樣)

下面是我試圖從控制台獲取輸入的 Java 代碼的一部分。 注釋是我在調試時在 watch 部分看到的值:

public static void main(String[] args) {

    Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
    int t = in.nextInt(); // t: 3, in.nextInt(): 3 as expected

    for (int i = 1; i <= t; i++) { // i: 1, t: 3, in.nextInt(): 3 (not sure which "3")
        int row = in.nextInt();
        // after this line in.nextInt(): 101 and row: 0 which are all WEIRD
        int column = in.nextInt();
        // now here it's in.nextInt(): 2 and column: 2

        int world[][] = new int[row][column];

        // in.nextInt(): 11 now and as we see it changed its value when I didn't even call it

        TreeMap<Integer, ArrayList<int[]>> distancesRandAcc = new TreeMap<Integer, ArrayList<int[]>>();
        distancesRandAcc.put(0, new ArrayList<int[]>());

        for (int j = 0; j < row; j++) {
            int temp = in.nextInt();
            char[] s = Integer.toString(temp).toCharArray();
            for (int k = 0; k < column; k++){
                world[j][k] = Character.getNumericValue(s[k]);
            }
        }
        int result = calculateDeliveryTime(world, row, column, distancesRandAcc);
        System.out.println("Case #" + i + ": " + result);
    }
}

這做了一些超出“常識”的奇怪事情。 在將所有輸入放入 IntelliJ 控制台后,我正在逐行調試,似乎 in.nextInt() 無法停止在隨機行獲取隨機數量的令牌,無論我是否調用它

當我嘗試在逐行調試的同時逐行輸入輸入時,似乎一個調用 of.nextInt 正在要求兩個 int 值。 (我輸入了一個數字並輸入,但它仍然等待另一個輸入,同時停留在同一行,其中 .nextInt() 只被調用一次)

在這一點上,我感覺我的調試過程是錯誤的,或者至少是一些外部問題,而不是代碼本身。 我可能是錯的,因為我仍然認為自己是新手......

拜托,有經驗的人可以教我如何解決這個問題嗎? 我發現一些問題與 .nextLine() 和 .nextInt() 有類似的問題,但不完全是這個。 如果它真的是重復的,我提前道歉,雖然......

(如果需要,我會添加更多信息)

您正在調用nextInt() ,因此輸入000被解析為數字0 ,因此int返回值為0 因此Integer.toString()將返回字符串"0" 你為什么對此感到驚訝?

由於您實際上並不關心作為數字的輸入,因此只需使用next

for (int j = 0; j < row; j++) {
    String s = in.next();
    for (int k = 0; k < column; k++) {
        world[j][k] = Character.getNumericValue(s.charAt(k));
    }
}

更新

這是用於讀取輸入的問題代碼的唯一問題。 不知道calculateDeliveryTime是否有問題。

請參閱IDEONE以獲取證據。 calculateDeliveryTime方法只是簡單的打印二維數組,所以可以看出輸入已經處理好了。

暫無
暫無

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

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