Java 如何使用扫描仪(BlueJ)
我是java新手,我的任务是使用扫描器读取数组中的数据,并在另一个方法中读取int。这是我目前所拥有的:Java 如何使用扫描仪(BlueJ),java,arrays,java.util.scanner,bluej,Java,Arrays,Java.util.scanner,Bluej,我是java新手,我的任务是使用扫描器读取数组中的数据,并在另一个方法中读取int。这是我目前所拥有的: 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[]
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);
}
publicstaticvoidmain(字符串[]args){
扫描仪=新的扫描仪(System.in);
系统输出打印(“输入n:”);
int sz=scanner.nextInt();
System.out.println(“输入石头的位置:”);
int[]数组=新的int[sz];
对于(int i=0;i问题就在这里而(x=1
(假设您实际输入了一些数字),并且您似乎从来没有更新过这2个数字中的任何一个。
因此x
始终是真的
,您永远不会脱离循环
现在我不能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");
}
公共静态无效跳转(int[]数组,int amtStone){
int x=0,moveOK=1,jumpedLoc=0,jumpedCount=1;
//x:计数器,移动ok:当为1时,可以继续。否则,跳转不可能。
//jumpedLoc:跟踪兔子的当前位置
//jumpCount:计算跳转的数量
while(x)你希望得到什么样的输出?为什么?是什么让你认为问题不在jump()
方法上?你有任何异常吗?你发布的代码没有问题。你能发布jump方法吗?好吧,说来话长。我要做的是计算达到最后一个数字所需的最小跳跃次数(作为河流的另一边)数组中的整数表示河流中石头的位置,另一个整数表示石头的数量。最长跳跃距离为50。好的,请更新问题,添加您的jump()
方法定义,它应该做什么,期望的输出是什么,因为你发布的代码工作得很好。请不要在这里正确解析输入。编辑问题嗯…所以我需要在if语句后面有一行x++吗?不确定你的意思,但额外的部分是这个amtStone--;
尽管这个mi可能是错的。因为我不太确定你打算做什么。此外,根据if声明,我知道条件是错误的,但我没有想到另一种方法……我会澄清我的问题。请稍等。
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");
}