OutOfMemoryError: Java heap heap when trying to read 5 int into an array

I am training for examples of more recent interviews for Java. I am trying to write a program to find duplicate numbers from 1 to N , where N is set by the user along with the numbers themselves. Here is the code:

 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); } } } 

But I get the following error in Eclipse Neon:

 Enter the number of numbers 5 Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at DuplicateNumbers.main(DuplicateNumbers.java:14) 

What's wrong? Why is the JVM heap space error? The code compiles and works fine.

+6
source share
3 answers

DataInputStream is for binary, not text. When you enter 4 bytes, this turns into a 32-bit int value, for example. 5, \ n, \ n, \ n - about 900 million, so it complains about memory when creating an array. You can verify this by running the code in your debugger.

You need text input, try using

 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. 
+20
source

Start here:

 DataInputStream in=new DataInputStream(System.in); 

You should not use DataInputStream ... and I see that you already have explanations about this.

But besides this:

 for(int e=0; e<a; e++) 

You immediately hit num [d] and num [e] equal. Since your second loop actually compares num [0] with num [0], for example. So: the second cycle should only work on indices after the external!

In addition, it is also unclear whether you want to โ€œduplicateโ€ 50 times if you entered a 50-fold number. I would rather go and print the number of duplicates for the number.

In other words: after fixing the problem with the input stream, your code will still not do the right thing.

And besides: using single-character names makes it almost impossible to easily understand what this code does.

+5
source

Try using Scanner for your class.

Here is a basic example:

 public static void main(String[] args) throws IOException { System.out.println("Enter a number: "); Scanner sc = new Scanner(System.in); String item = sc.next(); System.out.println("Your item is: " + item); sc.close(); } 
+2
source

Source: https://habr.com/ru/post/1014765/


All Articles