2014-09-27 75 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