Ami*_*Dev 6 java out-of-memory
我正在练习Java新手采访编码示例.我试图写一个程序,找出之间的重复数1到N,其中N由用户与数字本身沿中给出.这是代码:
import java.io.DataInputStream;
import java.io.IOException;
public class DuplicateNumbers {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(System.in);
System.out.println(" Enter the number of numbers ");
int a = in.readInt();
int[] num = new int[a];
System.out.println(" Enter the ints one by one ");
for (int b = 0; b < a; b++) {
System.out.println(" Enter no "+(b+1));
num[b]=in.readInt();
}
int c = 0;
for (int d = 0; d < a; d++) {
int f = 0;
c = num[d];
for (int e=0; e<a; e++) {
if (c==num[e]) {
f++;
}
}
if(f > 1)
System.out.println(" Duplicate number "+c);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我在Eclipse Neon中遇到以下错误:
Enter the number of numbers
5
Exception in thread "main" java.lang.OutOfMemoryError:
Java heap space at DuplicateNumbers.main(DuplicateNumbers.java:14)
Run Code Online (Sandbox Code Playgroud)
怎么了?为什么JVM堆空间错误?代码编译并运行正常.
Pet*_*rey 20
DataInputStream用于二进制而不是文本.当你输入4个字节时,它会变成一个32位的int值,例如5,\n,\n,\n大约是9亿,这就是为什么它会在你创建数组时抱怨内存的原因.您可以通过逐步调试调试器中的代码来检查这一点.
你需要的是文本输入,尝试使用
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of numbers");
int a = in.nextInt();
in.nextLine(); // discard the rest of the line.
Run Code Online (Sandbox Code Playgroud)
从这里开始:
DataInputStream in=new DataInputStream(System.in);
Run Code Online (Sandbox Code Playgroud)
你不应该使用DataInputStream......而且我看到你已经得到了解释.
但除此之外:
for(int e=0; e<a; e++)
Run Code Online (Sandbox Code Playgroud)
您将立即遇到num [d]和num [e]相等.因为你的第二个循环实际上比较num [0]和num [0].所以:第二个循环只需要在外部索引之后运行索引!
除此之外,如果您输入相同数量的50倍,还不清楚您是否真的需要50次"重复".我宁愿去打印一个数字的重复数量.
换句话说:在修复输入流问题之后,您的代码仍然无法正确执行.
除此之外:使用单字符名称几乎不可能轻易理解此代码的作用.
| 归档时间: |
|
| 查看次数: |
564 次 |
| 最近记录: |