通过扫描仪更新二维数组
我是 Java 和一般编程的新手。我最近开始使用数组,并在书中发现了一个练习,我认为我应该尝试一下。目标是使用扫描仪类读取文件,将每个数字分配给二维数组中的不同单元格。这就是我所拥有的方法。但无论我如何改变它,我似乎都无法得到想要的结果。要么我最终得到每个单元格中的最后一个数字,要么我收到错误。请帮忙。
int row = 0;
int col = 0;
while (A[row][col] != -1)
{
for (row = 0; row < A.length; row++)
{
for (col = 0; col < A[row].length; col++)
A[row][col] = scan.nextInt();
}
}
I'm new to Java, and programming in general. I recently started working with arrays, and came upon an exercise in the book that i thought id give a try. The goal is to read a file using the scanner class assign each number to a different cell in a 2d array. This is what i have for the method. But no matter how i change it, i cant seem to get the desired result. Either i end up getting the last number in every cell, or i get an error. Please help.
int row = 0;
int col = 0;
while (A[row][col] != -1)
{
for (row = 0; row < A.length; row++)
{
for (col = 0; col < A[row].length; col++)
A[row][col] = scan.nextInt();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
扫描需要在最内层循环中进行。此时,您可能需要重新阅读您正在阅读的章节,并在发布到 SO 之前花一些时间来解决问题。
您可能还会发现在观看程序执行时打印出值很有用。在
temp
中读取的位置之后添加System.out.println(temp)
。这样一来问题就很明显了。您还需要更改while
循环构造。就目前而言,这没有多大意义。The scanning needs to happen in the inner-most loop. At this point, you might want to re-read the chapter you're on and spend a bit longer working on problems before posting to SO.
You might also find that printing out values is useful while watching programs execute. Add
System.out.println(temp)
after the point where you read intemp
. This would have made the problem obvious. You'll also want to change yourwhile
looping construct. As of now, it doesn't make much sense.根据您的评论...这应该满足您的要求。您遇到的问题是,如果外部循环没有某种条件,您就无法摆脱内部循环。
请注意,我将
A
更改为a
;变量永远不应该以大写字母开头。我个人不会使用嵌套循环,而是走这条路:
Based on your comments ... this should do what you're asking. The problem you're having is that you're not able to break out of your inner loop without having some sort of conditional on the outer one.
Note that I changed
A
toa
; variables should never start with uppercase.I personally wouldn't use the nested loops, and go this route: