英文:
extract integers from file and print it using array in Java
问题
package foundations;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class gnfmd {
public static void main(String[] args) throws IOException
{
int[] array = new int[40];
int i = 0;
File file = new File("hello.txt");
if (file.exists())
{
Scanner hello = new Scanner(file);
System.out.println("文件已找到");
while (hello.hasNext() && i < array.length)
{
array[i] = hello.nextInt();
i++;
}
hello.close();
for (int l : array)
{
System.out.println(l);
}
}
else
{
System.out.println("文件未找到");
}
}
}
我在 Java 课程中遇到了这个问题。这个练习要求从一个 .txt 文件中提取所有整数,并使用数组打印它们,但即使我从模范答案中复制,它仍然会打印出零。请问有人可以告诉我我在哪里出错了吗?
英文:
package foundations;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class gnfmd {
public static void main(String[] args) throws IOException
{
int[] array = new int[40];
int i = 0;
File file = new File("hello.txt");
if (file.exists())
{
Scanner hello = new Scanner(file);
System.out.println("file found");
while (hello.hasNext() && i < args.length)
{
array [i] = hello.nextInt();
i++;
}
hello.close();
for (int l : array)
{
System.out.println(array[l]);
}
}
else
{
System.out.println("file not found");
}
}
}
I came across this problem during the java course. the exercise requires to extract all the integers from a .txt file and print them using arrays but it kept printing zeros even when I copy it from the model answer. can anyone please tell me where I have mistaken
答案1
得分: 1
你正在打印System.out.println(array[l]);
。你应该打印System.out.println(l);
,因为在for (int l : array)
循环的每次迭代中,l
已经包含了与array
不同的整数。因此,在第一次迭代中,l
将保存array[0]
的值,在第二次迭代中将保存array[1]
的值,依此类推。此外,你只初始化了数组的前args.length
个位置,这就是为什么它打印出零的原因,因为int
数组的所有位置的默认值都是零,而你没有为大多数甚至全部这些位置赋予任何其他值。
示例:
public class MyClass {
public static void main(String args[]) {
int[] array = {1,25,46,97};
for (int i : array) {
System.out.println(i);
}
}
}
输出:
1
25
46
97
英文:
You are printing System.out.println(array[l]);
. You should be printing System.out.println(l);
, because l
already holds a different integer from array
on each iteration of the for (int l : array)
loop. So on the first iteration, l
will hold the value of array[0]
, on the second iteration it will hold array[1]
, etc. That and the fact that you only initialize the first args.length
positions of the array are the reasons why it prints zeros, since the default values for all positions of an array of int
are zeros, and you aren't assigning any other value to most, if not all, of those positions.
Example:
public class MyClass {
public static void main(String args[]) {
int[] array = {1,25,46,97};
for (int i : array) {
System.out.println(i);
}
}
}
Output:
1
25
46
97
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论