Why do arrays do not accept input greater than their length? - java

I have noticed when inputting an integer into an array that if the integer is larger than the arrays length it will throw an out of bounds exception. Why is this? Why can the array not accept any integer value? How can I correct this when I need to store integers larger than an arrays length.
Thank you!
Here is the code. When I enter an integer greater than 5 I get an out of bounds exception. If I enter integers less than 5 the code works perfectly.
public class NumOfOccur
{
static Scanner input = new Scanner(System.in);
static int[] cards = new int[5];
static int[] numOccurence = new int[5];
public static void main(String[] args)
{
System.out.println("Enter five values: ");
for (int i = 0; i < 5; i++)
{
System.out.print("Card " + (i + 1) + " : ");
cards[i] = input.nextInt();
}
containsPair(cards);
}
public static boolean containsPair(int hand[])
{
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
for (int i = 1; i < numOccurence.length; i++)
{
if (numOccurence[i] > 0)
System.out.println("The number " + i + " occurs " + numOccurence[i] + " times.");
}
return false;
}
}

What you are suggesting here is wrong. An array of integers can hold any integer. When you are storing an integer into an array (or any value for that matter) you have to make sure that the index you are inserting it into is valid.
For example
//perfectly valid
int[] foo = new int[1];
foo[0] = 500;
I suspect what you are doing is something like this.
//throws index out of bounds exception
int[] foo = new int[1];
foo[500] = 500;
Note the difference here. the number inside the [] on the left side of the assignment operator indicate the index you are working with.
Based on your now posted code, your problem is here:
for (int i = 0; i < hand.length; i++)
numOccurence[hand[i]]++;
To briefly explain what is going on.
1) you first initialize numOccurence to a length of 5 integers.
2) You are putting user input into the cards[] then you pass the cards array into into the function containsPair()
3) If the user enters a number greater than 5, lets say 7 the operation hands[i] would be 7. This would be the same as numOccurence[7] which is out of bounds

Without any code, I'm assuming you're just misunderstanding what you're doing with your array. You just have to make sure you're accessing a valid index. There's no restriction on what integer you can store in an integer array.
// Make an array of length ten
int[] myIntArray = new int[10];
System.out.println(myIntArray.length);
// Set the first value in the array to 99: perfectly legal
myIntArray[0] = 99;
System.out.println(myIntArray[0]);
// The following line throws ArrayIndexOutOfBoundsException
myIntArray[99] = 100; // The last index in the array is only 9, not 99!
System.out.println(myIntArray[99]); // This line would also crash, for the same reason

Having seen your code, I think the issue is with this:
First, your numOccurence array always has a length of 5, but in the line
numOccurence[hand[i]]++;
You will get the OutOfBoundsException if hand[i] is 5 or greater (meaning you typed in a value of 5 or greater).
To fix this you should either:
Put restrictions on what card values the user can enter
Make that line numOccurence[i]++ if you mean to keep track of the number of times each card position was drawn
Make numOccurence a longer array so it can store the number of times each possible card (e.g. 1 to 13 for Ace to King) has occured.

I'm definitely sure the question is wrong. You're saying this is not possible
int[] anArray = new int[10];
anArray[5] = 20;
Which is obviously not true.
If that's what you're saying, post your code, because you have a bug.
If you want to make your array larger or something, you should consider using an ArrayList or something similar. Post your code so we can help you.

Related

Why does this method only return values of 0 to a new array?

I am supposed to write a short program that takes 10 numbers, stores the values in an array, passes it to a method (eliminateDuplicates()) that creates a new array of only the unique values from the first array.
However, I am having trouble either initializing the output array, or making the eliminateDuplicates() method return the output array properly. The output array is always full of 0's and I cannot figure out why this is failing.
java.util.Arrays.parallelSort(inputNumbers); //sorts the array in ascending order
eliminateDuplicates(inputNumbers); //passes array to eliminateDuplicates method
//display each unique value in output array
System.out.print("The distinct numbers are ");
for(int i = 0; i < outputNumbers.length; i++)
System.out.print(outputNumbers[i] + " ");
}
public static int [] eliminateDuplicates(int[] list) {
int[] outputNumbers = new int [list.length];
int k = 0;
for (int i = 0; i < list.length; i++)
if(i == 0) //compares each array value against preceding value
outputNumbers[i] = list[i]; //only copies unique values to output array
else
if(list[i] != list [i-1]) {
outputNumbers[k] = list[i];
k++;
}
return outputNumbers;```
You have a local outputNumbers in eliminateDuplicates which you return. I assume you also have a redundant static outputNumbers. Option 1: Eliminate the local variable, change
int[] outputNumbers = new int [list.length];
to
outputNumbers = new int [list.length];
Option 2: Set outputNumbers on call (which is what I would likely do, and eliminate the static one)... Like,
int[] outputNumbers = eliminateDuplicates(inputNumbers);
Don't forget to remove the static one if you use option 2.
You are ignoring the array returned by your method.
Change
eliminateDuplicates(inputNumbers);
to
int[] outputNumbers = eliminateDuplicates(inputNumbers);
P.S. your output array has the same length as the input array. Therefore, since you are eliminating duplicates, it may have some 0s as its last elements. If that's not what you want, you should create the output array only after you find out how many unique numbers the input array has.

How to get get rid of duplicate values in an int array?

The question is as the title says, how would I get rid of duplicate values in an integer array? I want to have it so the user inputs five numbers, all ranging between 10 and 100. The catch is that I have to have it so that if the value they are inputting has already been input into the array it will not count. Here is the code I have so far:
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int[] intArray = new int[5]; //max of 5 values
for(int i = 0; i < 5; i++){
System.out.println("Please enter your desired number that is between 10 and 100: ");
intArray[i] = input.nextInt(); //puts the value into the array
}
System.out.println(Arrays.toString(intArray)); //for test purposes to make sure the array was correctly taking in the values
}
}
System.out.println(Arrays.toString(intArray)); //for test purposes to make sure the array was correctly taking in the values
I am confused on how I would make it so if the user inputs a number that already exists in the array it will just not add it. Here is an example of what I mean, say the user inputs the numbers 15, 22, 46, 46, 77 once the program is done looping five times it will print out the following: [15, 22, 46, 77]. I am stuck on how to do this. Also I have edited out the if the number is between 10 and 100 if statements for it to be easier to read, and get to the main point at hand.
What about using a Set? A LinkedHashSet, in particular, allows you to do this in O(n) time and memory, while retaining the order of the inputs. And before you say "But I can't use a HashSet," you'll need its behavior for the optimal solution, so the followup question might be "How would I implement a LinkedHashSet, possibly baking the logic into my program?"
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<Integer> intSet = new LinkedHashSet<>();
int[] intArray = new int[5]; //max of 5 values
for (int i = 0; i < 5; i++) {
System.out.println("Please enter your desired number that is between 10 and 100: ");
intSet.add(input.nextInt());
}
int[] intArray = new int[intSet.size()];
int i = 0;
for (Integer val : intSet) {
intArray[i++] = val;
}
}
You're saying you want a variable number of numbers at the end, so an array is not the right choice here, use an ArrayList instead.
Something like:
List<Integer> intList = new ArrayList<Integer>();
int maxElements = 5; //Set max value here
for(int i = 0; i < maxElements ; i++)
{
System.out.println("Please enter your desired number that is between 10 and 100: ");
Integer newNumber = input.nextInt();
if(newNumber >= 10 && newNumber <= 100)
{
Boolean found = false;
foreach (Integer check : intList)
{
if (check == newNumber)
{
found = true;
break;
}
}
if (!found) intList.Add(newNumber);
}
else if(newNumber < 10 || newNumber > 100)
{
System.out.println("Enter a valid number next time, this number will not be counted in the results.");
}
}
Duplicate check: that inner loop I added checks if there is another element with the same value, and in that case skips the number as you said.
I wrote this without a computer, so I could have mixed some stuff up, but you get the general idea.
If you just have to select unique numbers from the numbers that a user will input, don't store them in an Array initially.
Instead, store them in a HashMap/Hashtable and then once the user input is finished convert it to an Array.
Another way of doing this would be to use the Set Collection. Add each number you receive to an instance of the Set and finally convert the Set to an Array. Set will maintain uniqueness by default.
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int[] intArray = new int[5]; //max of 5 values
Set<Integer> uniques = new HashSet<Integer>();
for(int i = 0; i < 5; i++){
System.out.println("Please enter your desired number that is between 10 and 100: ");
uniques.add(input.nextInt()); //puts the value in the set
}
System.out.println(Arrays.toString(uniques.toArray())); //for test purposes to make sure the array was correctly taking in the values
}
A one liner would accomplish what you want:
Set<Integer> noDuplicates = new LinkedHashSet<>(Arrays.asList(intArray));
Do this after you read the values and store them in your intArray.
If you want to preserve the order in which the values were entered, use a LinkedHashSet, otherwise use just a HashSet.
A Set is a collection that cannot have duplicates.
make your array size 100 and using input as a index. before update array[input] = input, check the value of the index (input number) of the array.
use a map store input values as a key. before save the value in array, check whether key is in a map or not.

Creating a custom sort for an array of integers?

Right, so I have a 2 part sorting algorithm. It's all based on an array of 14 random integers. For example:
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
Now, the first thing I'm trying to figure out how to do is to count how many a certain number exists in the original array. So, we know that 1 exists once, and 2 exists four times in the original array. But as easy as it is to visually see this, what if we don't have access to the original array. So I need to craft a method that will count how many of each number 1-9 exists and put this in a new array called count. So that index 0 in count would represent the integer 1 and would have a value of 1. Index 1 will represent the integer 2 and have a value of 4. And so on and so forth. Here is what I've got so far but I'm stuck. Sorting is pretty challenging for me.
public static void main(String[] args)
{
// int[] countFinal = {1,4,1,2,1,0,1,2,2}; // The number of times a number 1-9 appears in a[].
// int[] sortedFinal = {1,2,2,2,2,3,4,4,5,7,8,8,9,9}; // What we need as a final product.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//int[] count = {};
int[] sorted = {};
countHowMany(a, 1);
countHowMany(a, 2);
countHowMany(a, 3);
countHowMany(a, 4);
countHowMany(a, 5);
countHowMany(a, 6);
countHowMany(a, 7);
countHowMany(a, 8);
countHowMany(a, 9);
}
public static int countHowMany(int[] array, int value)
{
// Gathering a count for how many times a number 1-9 exists and adding it to count[];
int howManyCount = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
howManyCount++;
}
}
System.out.println(howManyCount);
count = new int[9];
count[howManyCount];
System.out.println(Arrays.toString(count); // Testing the input
return howManyCount;
}
It appears to count the number of times an item in the array exists properly. Now I just gotta figure out how I can add that value into a new array count[] and do it for each countHowMany(). This is the part I'm stuck on.
Once I have figured out count[] I can use it to create sorted[]. Now what sorted is supposed to do is take the data from the original array and count[] and create a new array that sorts it in ascending order and allows duplicates. So, since 1 occurs once and 2 occurs four times, the new array would be sorted[] = {1, 2, 2, 2, 2, ...}
It's a relatively small program and a small amount of integers, so it's ok that I create array's as necessary. The key being that I'm limited to using arrays and cannot use say ArrayLists for this.
You don't need to count each value individually. You can just iterate through the entire array and increment your counters for each element as you encounter it.
int counts = new int[20]; // Choose a value that's bigger than anything in your array.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
for (int value : a) {
counts[value]++;
}
If you don't know what the largest value in your array is likely to be, you're better to use either a Map to store the counts, or some kind of List that you increase the size of as needed.
You're better off just going through the array once and incrementing a counter for each value that might appear:
int counts[] = new int[10];
for (int n: array)
counts[n]++;
That's enough to put the count for each n in counts[n]. You can then read the values out of your count[] array.
You might not have come across this syntax for a for loop over an array, by the way. It's equivalent to
int counts[] = new int[10];
for (int i=0; i<array.length; i++) {
int n = array[i];
counts[n]++;
}
but it's less verbose.
Your method may as well be void, since you're not doing anything with the returned values of your countHowMany function. This will accomplish what you want:
public static void main(String[] args)
{
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//count the instances of each number in the array
int[] count = new int[9];
for(int i = 0; i < count.length; i++)
count[i] = countHowMany(a, i+1);
//put the values in the sorted array
int[] sorted = new int[a.length];
int position = 0; // stores the place in the array to put the new digit
for(int digit = 0; digit < 9; digit++)
{
for(int inst = 0; inst < count[digit]; inst++)
{
sorted[position] = digit + 1;
position++;
}
}
System.out.println(Arrays.toString(sorted));
}
The issue with your code is that you were trying to create the count array in each call of the countHowMany method, but this array is destroyed once the method finishes. The method calls should just return the counts, and then those returns should be put into the count array from outside the method. Note, however, that there are other ways to count the number of instances of each value, as noted by other answers.

ArrayIndexOutOfBoundsException when looping

I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.

Counting the least occurring in an array of 10 user input integers

LeastFrequent - Output the integer which occurs least frequently along with its occurrence count from a list of 10 integers input from System.in. If multiple integers in the list occur least frequently, output any integer that occurs least frequently. Name your class LeastFrequent. You can assume that all 10 integers are in the range -100 to 100 inclusive.
import java.util.*;
public class LeastFrequent
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arr = new int[10];
int[] hold = new int[300];
int x = 0;
int count = 0;
int a = 1;
int least = 0;
System.out.print("numbers: ");
//adds 10 numbers to an array and counts occurrence
for(int i=0;i<arr.length;i++)
{
arr[i] = scan.nextInt();
hold[arr[i]]++;
}
for(int i=0;i<hold.length;i++)
{
if(hold[i] > 0)
{
}
}
System.out.println("least frequent: " + count + " occurs " + arr[count] + " times");
}
}
I have it asking the user for 10 integers and putting it into the array.
I also have it counting the occurrence of the input numbers and storing it in another array.
I am stuck on finding the least frequent one.
I know i need to scan through the second array again bu i dont know how.
Any thoughts on how to compare the element's values of the second array while skipping the values that equal 0?
Firstly, the following isn't quite correct:
hold[arr[i]]++
What would happen if I input -1?
As to finding the least occurring element, you need to find the smallest value in hold that's greater than zero. As you iterate over hold, you could keep track of the smallest such value seen so far as well as its index.
Finally, an alternative approach to the problem is to sort the array. Once you do this, equal values are brought next to each other. This simplifies counting the repetitions.

Categories