2014-09-27 45 views
0

我新的Java和我的任務是用掃描儀在陣列中,而在另一個method.This一個int閱讀是我到目前爲止有:如何使用掃描儀(BlueJ的)

public static void main(String[] args){ 
Scanner scanner = new Scanner(System.in); 
System.out.print("Enter n: "); 
int sz = scanner.nextInt(); 
System.out.println("Enter locations of stones: "); 
int[] array = new int[sz]; 
for (int i=0;i<array.length;i++){ 
array[i] = scanner.nextInt(); 
} 
jump(array,sz); 
} 

我想從開始這樣的閱讀方法:

public static void jump(int [] array, int amtStone){ 
int x =0, moveOK =1, jumpedLoc =0, jumpedCount =1; 
//x: counter, moveOK: when 1, it is ok to continue. Otherwise, the jump is impossible. 
//jumpedLoc: to keep track of the current location of the rabbit 
//jumpCount: to count the amount of jumps 
while (x<amtStone) 
{if(array[x+1]-array[x]<=50){ 
jumpedLoc = array[x+1]; 
jumpedCount++;} 
} 

if (moveOK ==1) 
System.out.println(jumpedCount); 
else 
System.out.println("-1"); 

} 

我在做什麼是計算的最小數量的跳躍需要一隻兔子到達河對岸。數組中的整數表示從起點開始的石頭距離作爲河流的一側,另一個int表示石塊的數量。兔子可以跳的最大距離是50。

用於輸入和輸出:

輸入n:7(輸入,結石在河數) 32 46 70 85 96 123 145(輸入,距離在石頭和起點之間,最後一個數字是河流的寬度,即目的地(河流的另一邊)和起點之間的距離) 輸出:3(這是最小的次數a兔子可以跳)

如果不可能,則輸出爲-1。

當我運行主要方法,輸入int和數組後,沒有輸出,程序沒有繼續。我不確定接下來要做什麼。

+0

你期望的輸出?爲什麼? – 2014-09-27 01:46:54

+0

是什麼讓你認爲問題不在'jump()'方法?你有什麼例外嗎?您發佈的代碼沒有問題。你可以發佈跳轉方法嗎? – qbit 2014-09-27 01:49:39

+0

那麼,這是一個漫長的故事。我正在做的是計算達到最後一個數字所需的最小跳數(作爲河流的另一邊)。數組中的整數代表河流中的石頭位置,另一個int代表石頭的數量。跳躍的最長距離爲50. – Melody 2014-09-27 01:55:22

回答

0

問題在這裏​​。你遇到了無限循環。

這是不是很清楚你想要做什麼,但你檢查x < amtStone。但x == 0amtStone >= 1(假設你實際上輸入了一些數字),並且你從來沒有更新過任何這些數字。

所以x < amtStone總是true,你永遠不會跳出循環。

現在,我不是100%確定什麼是你想實現你的代碼,但我認爲這是你想要什麼:

public static void jump(int [] array, int amtStone){ 
    int x =0, moveOK =1, jumpedLoc =0, jumpedCount =1; 
    //x: counter, moveOK: when 1, it is ok to continue. Otherwise, the jump is impossible. 
    //jumpedLoc: to keep track of the current location of the rabbit 
    //jumpCount: to count the amount of jumps 

    while (x<amtStone){ 

    //complete the code here. { 
     if(array[x+1]-array[x]<=50){ 
      jumpedLoc = array[x+1]; 
      jumpedCount++; 
     } 
     amtStone--; 
    } 
    if (moveOK ==1) System.out.println(jumpedCount); 
    else System.out.println("-1"); 
} 
+0

hmm ...所以我需要在if語句之後的一行x ++? – Melody 2014-09-27 02:17:03

+0

不確定你的意思,但額外的部分是這個'amtStone - ;'雖然這可能是錯誤的。因爲我不太清楚你打算做什麼。 – qbit 2014-09-27 02:20:07

+0

此外,根據if語句,我知道條件是錯誤的,但我只是沒有想到另一種方式做到這一點...... – Melody 2014-09-27 02:23:53