ArrayIndexOutOfBoundsException when looping - java

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.

Related

Math.random() and Random::nextInt always give the same exact number inside a for loop

So I am trying to make an Array with random numbers, but whenever I try Math.random or create a new Random object and use it, I always get the same number multiple times. My code is this one:
int[] Array = new int[size];
for (int Y : Array) {
Array[Y] = (int) (Math.random() * 10) + 3;
}
or this one:
int[] Array = new int[size];
for (int Y: Array) {
Array[Y] = rand.nextInt(30);
}
The output im getting is: [0][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3][3]
I haven't set a seed and I tried it outside the loop and inside but still only get the same number.
You are not referring to the index of the array, but to the specific element which remains the same. You have to use indexed loop.
Try with that (it is a good practice to use camelCase for variables, so 'Array' starting with small 'a')
int[] array = new int[size];
for(int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(30);
}

Java: Simple array splitting program

I am trying to make a simple Java program where you input 15 numbers (INTS, positive and negative) first, let's say these will get loaded into arrayOne. After that all numbers that are below '-5' need to be loaded into a second array (arrayTwo). I want to print all numbers of arrayTwo, while still retaining all arrayOne numbers.
I know my code doesn't make any sense at all, as I am still a beginner (about a month on and off). This is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int[] arrayOne = new int[15];
int count = 0;
System.out.println("Input 15 ints: ");
for (int i = 0; i <= arrayOne.length-1; i++){
arrayOne[i] = scanner.nextInt();
if (arrayOne[i] < -5){
count++;
}
}
int[] arrayTwo = new int[count];
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayOne[i] = arrayTwo[i];
}
}
}
}
It's so confusing for me. I don't know what to do to be honest. Do I need to use some kind of nested loop?
Thank you so much in advance, any help will be greatly appreciated.
int[] arrayTwo = new int[count];
int index = 0;
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayTwo[index++] = arrayOne[i];
}
}
index will be used to write into the second array.
index++ is postfix increment operator. You can read about that here - Java: Prefix/postfix of increment/decrement operators?
You were doing the assignment the wrong way. It must be arrayTwo[..] = arrayOne[..] to assign a value from arrayOne into arrayTwo.
I know my code doesn't make any sense at all, as I am still a beginner
You don't need to apologize for being a beginner. We were all there once. Your code has the general right idea. You are just missing a few key concepts.
Look at this line:
arrayOne[i] = arrayTwo[i];
You are assigning values from arrayTwo into arrayOne. However, from what you say, you want it the other way around:
arrayTwo[i] = arrayOne[i];
But now you are assigning to the same index in arrayTwo as you are reading from in arrayOne. This will leave 0 values where the original values in arrayOne were larger than -5. I doubt this is what you want.
Instead, you should use two separate indexes for each array. Maybe i1 and i2. These will increment independently. That is i1 will always increment in the for loop because you are stepping over the elements of arrayOne. But i2 should only increment when you write a value into arrayTwo.
In arrayOne you have 15 integers.But in arrayTwo you have integers that are below -5.
Then you have to understand that size of the arrayTwo is less than(in many cases) or equal to size of arrayTwo.Reason is that the integers below -5 is a subset of integers.
Therefore using same iterator using while loop for two arrays will make an error.
instead using a second for loop , modify the code as below,
int indexArrayOne = 0,
indexArrayTwo=0;
while(indexArrayOne < arrayOne.length){
if(arrayOne[indexArrayOne] < -5){
arrayTwo[indexArrayTwo++] = arrayOne[indexArrayOne];
}
indexArrayOne++;
}
You can use a for loop like what you have done for this.The idea is you have to use two iterators for two arrays.
Use ArrayList for arrayTwo, so that you can hav all element in arrayTwo in just single for loop.
List<Integer> arrayTwo = new ArrayList<>();
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayTwo.add(arrayTwo[i]);
}
}
you can use streams and lambda in this code.but first you have learn Stream API & lambda

Filling two new arrays from existing array

I already have one Array with random numbers between 0-999.
I also have created two new arrays, one with correct the size to hold all numbers 0-499, and one with the correct size for numbers 500-999.
Problem is to then loop through the Array holding all numbers and copying the right numbers 0-499 and 500-999 to the new Arrays.
Anyone know the correct way to do this? Have spent many days now trying to figure this out.
What i got so far:
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
Random generator = new Random();
System.out.print("How many numbers between 0 - 999?" );
int number= scannerObject.nextInt();
int [] total= new int[number];
for(int index = 0; index < total.length; index++ )
{
total[index] = generator.nextInt(1000);
}
System.out.println("Here are the random numbers:");
for(int index = 0; index < total.length; index++ )
{
System.out.print(total[index]+ " ");
}
int lowNumber=0;
int largeNumber = 0;
for(int index = 0; index < total.length; index++ )
{
if (total[index] < 500)
{
lowNumber++;
}
if (total[index] >= 500)
{
largeNumber++;
}
}
System.out.println();
System.out.println(lowNumber);
System.out.println(largeNumber);
int [] totalLownumber = new int [lowNumber];
int [] totalLargeNumber = new int [largeNumber];
for(int index = 0; index < total.length; index++ )
{ // TODO
}
}
2 of the approaches you can take are as follows:
You can go through the initial array, count the elements you have, and use the counter values to define the size of the arrays you need. You then go over the original array once again and copy the elements to their respective array. You can use the counter values once again (you would need to reset them first) to allow you to keep track in which array location will the current number need to go. This should be similar to what you are doing.
Consider using a variable length data structure such as a List (ArrayList in Java). This would allow you to go over your original array and assign the numbers to their respective list (let's call them largeNumberList and lowNumberList). Since these collections have a dynamic size, you would only need to traverse the array once and assign as you go along.
The latter approach is usually what is used more often, however, since it would seem that this question is related to homework, I would recommend you try both approaches and compare them.
Try this:
int lowIndex = 0;
int largeIndex = 0;
for(int index = 0; index < total.length; index++ ) {
if (total[index] < 500) {
totalLowNumber[lowIndex++] = total[index];
} else {
totalLargeNumber[largeIndex++] = total[index];
}

finding the number of pairs of numbers in an array that add up to a number

I am trying to come up with a program that will search inside of an array that is given a length by the user that picks out whether there is a pair of numbers that sum to 7. The idea is that if there is k amount of dice being thrown, how many pairs of numbers out of those dice thrown add up to 7. So far this is all that I could come up with but I am very stuck.
This is the driver class for the program. I have to write a class that will make this driver function properly.
import java.util.Scanner;
public class SevenDriver{
public static void main(String[] args){
System.out.println("Enter number of dice to toss");
Scanner s = new Scanner(System.in);
int diceCount = s.nextInt();
SevenTally t = new SevenTally(diceCount);
int experiments = 1000000;
int wins = 0;
for(int j = 0; j < experiments; j++)
if(t.experiment()) wins++;
System.out.println((double)wins/experiments);
}
}
This is what I have so far. It does not currently work or compile. I am just looking for some ideas to get me going. Thanks!
public class SevenTally{
private int diceCount;
public SevenTally(int die){
diceCount = die;
}
public int genDice(){
return 1 + (int)(Math.random()*6);
}
public boolean experiment(){
boolean[] nums = new boolean[diceCount];
int ranNum;
int sum = 7;
for(int i = 0; i < nums.length; i++){
ranNum = genDice();
if (nums[ranNum] == sum){
return true;
}
}
int left = 0;
int right = nums.length - 1;
while(left<right){
int tempSum = nums[left] + nums[right];
if(tempSum == 7){
return true;
}
else if(tempSum>7){
right--;
}
return false;
}
}
First populate your array of length k with random int in [1;6]
The number of possible pairs in an array of length k is the number of 2-combinations in the array, which is (k-1)*k/2 (http://en.wikipedia.org/wiki/Combination)
You can test all the possible pairs (i,j) in your array like so:
int win = 0;
int tally = 7;
for(int i=0; i<k-1; i++){
for(int j=i+1; j<k; j++){
if(array[i]+array[j] == tally){
win++;
}
}
}
What this does is that it sets the first element of the pair to be the first element of the array, and sums it with the other elements one after the other.
It pairs array[0] with array[1] to array[k-1] at the first pass of the i for loop, that's k pairs.
Then k-1 pairs at second pass, and so on.
You end up with (k)+(k-1)+(k-2)+...+1 pairs, and that's exactly (k-1)*k/2 pairs.
done =]
edit: sorry, haven't read the whole thing. the method experiment() is supposed to return a boolean. you can return win>0?true:false; for example...
This Wiki page has some algorithms to do that. Its not a trivial problem...
You're generating a random number in ranNum, and then using it as an index into the array nums. Meanwhile, nums never gets filled, so no matter which box you index into, it never contains a 7.
What you want to do, if I understand your problem correctly, is fill each space in the array with the result of a die roll, then compare every two positions (rolls) to see if they sum to seven. You can do that using a nested for loop.
Essentially, you want to do this: (written in pseudocode as I'm not a java programmer)
int[] results[numrolls]
for (count = 0 to numrolls-1) { results[numrolls]=dieRoller() }
for (outer = 0 to numrolls-2)
for (inner = outer+1 to numrolls-1)
if (results[outer] + results[inner] == 7) return true
return false;
However, in this case there's an even easier way. You know that the only ways to get a sum of 7 on 2d6 are (1,6),(2,5),(3,4),(4,3),(5,2),(6,1). Set up a 6-length boolean array, roll your dice, and after each roll set res[result] to true. Then return (1-based array used for simplicity) ( (res[1] && res[6]) || (res[2] && res[5]) || (res[3] && res[4]) ).
ArrayIndexOutOfBoundsException means you are trying to access an element of the array that hasn't been allocated.
In your code, you create a new array d of length diceCount, but then you genDice() on always 6 elements.

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

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.

Categories