java.lang.ArrayIndexOutOfBoundsException: 2 >= 2 - java

I'm brand new to Java and my first assignment was to implement a "for" loop. I wrote this program in C++ and it compiles in Java, but I got an error at runtime. Can anyone tell me what's wrong?
import java.util.Scanner;
import java.util.Vector;
public class GlobalMembersMain
{
public static Vector<Integer> get_prime_factors(int number)
{
Vector<Integer> primefactors = new Vector<Integer>();
for (int j = 2; j <= number; j++)
{
if (number % j == 0)
{
primefactors.add(j);
number = number / j;
j = 1;
}
}
return primefactors;
}
public static void main(String[] args)
{
int number;
int count = 1;
System.out.print("Enter integer to analyse:");
System.out.print("\n");
Scanner scan = new Scanner(System.in);
number = scan.nextInt();
Vector<Integer> primefactors = new Vector<Integer>();
primefactors = get_prime_factors(number);
System.out.print("Prime factors are ");
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
else
{
System.out.print(primefactors.elementAt(a));
System.out.print(" (");
System.out.print(count);
System.out.print(") ");
count = 1;
}
}
System.out.print("\n");
}
}
The output:
Enter integer to analyse:
10
Prime factors are 2 (1) Exception in thread "main" java.lang.ArrayIndexOutOfBoun
dsException: 2 >= 2
at java.util.Vector.elementAt(Unknown Source)
at GlobalMembersMain.main(GlobalMembersMain.java:36)

for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
Is exceeding the size of the primefactors collection. By 2, in fact.
Change to primefactors.size() - 1 to avoid this error.

Arrays are zero based, which I imagine you are aware of. What you may not be aware of is that in Java a List is backed by an array as well. When you invoke primefactors.size() +1 you are getting one more than you would possibly want. For instance is pf is of size 1 your loop will do the following:
pf.get(0); //returns the only value in the list
pf.get(1); // element doesn't exist
Now the other thing is you do not want to use Vector, generally speaking in Java. It is a synchronized collection. What you want is List/ArrayList.
OTHER CODE ISSUES
public static Vector<Integer> get_prime_factors(int number)
this does not need to be static. Also naming convention is camel case in Java so your function name should be getPrimeFactors(int number)
GlobalMembersMain
Should most likely be named GlobalMember as classes are to be singular in nature and I believe you added Main to indicate it was the class that holds the main function.
In your main function you would do this:
GlobalMember member = new GlobalMember();
member.getPrimeFactors(number);

This is where the problem is:
for (int a = 0; a < primefactors.size() + 1; a++)
{
if (primefactors.elementAt(a) == primefactors.elementAt(a+1))
{
count++;
}
//...
primefactors.elementAt(a+1) for the last element in your collection will throw the exception (AIOB).

Remember that arrays, lists and vectors in Java are zero-based. In your case, the primefactors vector will consist of two elements, available at index 0 and 1 respectively.
The problem you are facing is that you try to access the element primefactors.elementAt(2) which does not exist.
One problem is the break condition in the loop:
for (int a = 0; a < primefactors.size() + 1; a++) {
// ...
}
The first time, a will be 0, the second time 1 which are both fine. However, the loop will not break the third time, because a will equal 2, which is less than primefactors.size() + 1. Consequently, there will be a call to primefactors.elementAt(2) which does not exist and the program will blow up.
There is also a second problem inside the loop since you increment the loop variable by one during the comparison:
if (primefactors.elementAt(a) == primefactors.elementAt(a+1)) {
// ...
}
Yet again, your program will fail if you pass 2 as an argument to primefactors.elementAt(...)

Related

Why does this for-loop only run once?

The goal of my code: To be able to write a program where I can enter in any number int as a command-line argument and displays how many digits in the integer number are 7s.
My problem is that I don't understand why my code only runs through the for-loop once. I inserted the system.out.println(sevens); to see how many times this loop works when I compile with a random number like 456789.
I could only think of a for-loop to use for this one and fixed some simple mistakes in the beginning. I also checked my brackets
public class TestingSevens {
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
int count = 0;
for (int i = 0; i < args.length; i++) {
if (sevens%10 == 7) {
count += 1;
}
sevens = sevens/10;
System.out.println(sevens);
}
System.out.println(count);
}
}
The result of inputting a number like 456789 is "45678" for the first print and the second print is "0." I know the number for some reason only runs through the loop once since it cuts off the last number before jumping out of the loop to print the count...any advice?
I presume you want to iterate over each digit of sevens. Since sevens initialized from args[0], the loop limit should match and look at args[0].length() rather than args.length.
for (int i = 0; i < args[0].length(); i++)
An alternate way to write the loop is to iterate until sevens reaches 0. That lines up better with the loop body; both use the same variable.
while (sevens > 0) {
if (sevens%10 == 7) {
count += 1;
}
sevens /= 10;
System.out.println(sevens);
}
Your code has logic errors, so to check if the iterated number is number 7 you need to turn the number into a string and check if the character is the desired character using: numberString.charAt(index)
Below is the corrected code:
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
String numberString = String.valueOf(sevens);
int count = 0;
for (int i = 0; i < numberString.length(); i++) {
char c = numberString.charAt(i);
if (c == '7') {
count += 1;
}
System.out.println("Input number: " + sevens);
}
System.out.println("Count of 7 numbers: " + count);
}

Array is printing more numbers than intended?

I'm supposed to create and initialize a 100-element array, then make the 7th element the number "7", and finally print the array, starting a new line every 20 elements. I've been trying to figure this out for a long time and I can't.
My code right now is:
public class Array {
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
}
public static void printArray(int[] array){
for (int a=0; a < array.length; a++) {
System.out.print(" " + array[a]);
if ((a - 1) % 20 == 0) {
System.out.println("");
}
}
}
}
When I run this my output is a lot of zeros, far more than 100. They are separated every 20 characters as intended, but the seventh element is not 7. I think it has to do with the association between int "a" and my array, but I can't figure it out. I know the solution must be simple but I just cannot see it. Thank you all!
Proper indentation of your code, in particular the main method, reveals what is going on. You are calling printArray from within the for loop, so you are printing the array contents 100 times.
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
Move the call to printArray after the } ending brace for the for loop.
Now you'll get 100 0s.
Also, I think you meant to have array[a] = a + 1; executed if the index was not 6, e.g.
if (array[a] == 6) {
array[a] = 7;
} else {
array[a] = a + 1;
}
Additionally, you will want to print a newline after 20 numbers, e.g. after indexes 19, 39, etc., so add 1 to a before calculating the remainder, instead of subtracting 1, so that 19 + 1 = 20, whose remainder is 0.
There are many things wrong. However, to answer your question, you are printing the array 100 times since printArray is inside your first loop.
You misplaced an end parenthesis in your main method. The properly formatted method looks like this:
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
}
array[a] = a + 1;
}
printArray(array);
}
First of all your code is organized very badly so it's very easy for u to miss what went where. You have 2 major mistakes, first of all you called printArray()
Inside your for loop and therefore printed it 100 times.
Second, you kept checking if the value inside the array in index a is 6.
You need to check if a is 6 since it is your index like this:
if(a == 6)
array[a] = 7;
Well, I ran your code, and there are a few places that can be corrected.
As for your problem of the many things being printed, that's because you've placed your printarray() inside the for loop, so it's printing the array 100 times.
As for printing it out, i find this code to be more concise:
public static void printArray(int[] array){
int counter = 0;
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
counter++;
if(counter == 20){
counter = 0;
System.out.print("\n");
}
}
}
Also, I'm not really sure why you're using a for loop to just change the 7th element. You could use this:
array[6] = 7;
I'm not really sure what you're doing in the for loop.
I hope this helped! Good luck!

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.

Efficient way of generating all combinations of 12 numbers that add to 100 in Java [duplicate]

This question already has an answer here:
How to iterate through array combinations with constant sum efficiently?
(1 answer)
Closed 9 years ago.
I have 12 products at a blend plant (call them a - l) and need to generate varying percentages of them, the total obviously adding up to 100%.
Something simple such as the code below will work, however it is highly inefficient. Is there a more efficient algorithm?
*Edit: As mentioned below there are just too many possibilities compute, efficiently or not. I will change this to only having a maximum of 5 or the 12 products in a blend and then running it against the number of ways that 5 products can be chosen from the 12 products.
There is Python code that some of you have pointed to that seems to work out the possibilities from the combinations. However my Python is minimal (ie 0%), would one of you be able to explain this in Java terms? I can get the combinations in Java (http://www.cs.colostate.edu/~cs161/Fall12/lecture-codes/Subsets.java)
public class Main {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
for(int a=0;a<=100;a++){
for(int b=0;b<=100;b++){
for(int c=0;c<=100;c++){
for(int d=0;d<=100;d++){
for(int e=0;e<=100;e++){
for(int f=0;f<=100;f++){
for(int g=0;g<=100;g++){
for(int h=0;h<=100;h++){
for(int i=0;i<=100;i++){
for(int j=0;j<=100;j++){
for(int k=0;k<=100;k++){
for(int l=0;l<=100;l++){
if(a+b+c+d+e+f+g+h+i+j+k+l==100)
{
System.out.println(a+" "+b+" "+c+" "+d+" "+e+" "+f+" "+g+" "+h+" "+i+" "+j+" "+k+" "+l);
}}}}}}}}}}}}}
}
}
Why make it so difficult. Think simple way.
To explain the scenario simpler, consider 5 numbers to be generated randomly. Pseudo-code should be something like below.
Generate 5 random number, R1, R2 ... R5
total = sum of those 5 random number.
For all item to produce
produce1 = R1/total; // produce[i] = R[i]/total;
Please, don't use nested for loops that deep! Use recursion instead:
public static void main(String[] args) {
int N = 12;
int goal = 100;
generate(N, 0, goal, new int[N]);
}
public static void generate(int i, int sum, int goal, int[] result) {
if (i == 1) {
// one number to go, so make it fit
result[0] = goal - sum;
System.out.println(Arrays.toString(result));
} else {
// try all possible values for this step
for (int j = 0; j < goal - sum; j++) {
// set next number of the result
result[i-1] = j;
// go to next step
generate(i-1, sum + j , goal, result);
}
}
}
Note that I only tested this for N = 3 and goal = 5. It absolutely makes no sense to try generating all these possibilities (and would take forever to compute).
Let's take your comment that you can only have 5 elements in a combination, and the other 7 are 0%. Try this:
for (i = 0; i < (1<<12); ++i) {
if (count_number_of_1s(i) != 5) { continue; }
for (j = 0; j < 100000000; ++j) {
int [] perc = new int[12];
int val = j;
int sum = 0;
int cnt = 0;
for (k = 0; k < 12; ++k) {
if (i & (1 << k)) {
cnt++;
if (cnt == 5) {
perc[k] = 100 - sum;
}
else {
perc[k] = val % 100;
val /= 100;
}
sum += perc[k];
if (sum > 100) { break; }
}
else { perc[k] = 0; }
}
if (sum == 100) {
System.out.println(perc[0] + ...);
}
}
}
The outer loop iterates over all possible combinations of using 12 items. You can do this by looping over all numbers from 1:2^12, and the 1s in the binary representation of that number are the elements you're using. The count_number_of_1s is a function that loops over all the bits in the parameter and returns the number of 1s. If this is not 5, then just skip this iteration because you said you only want at most 5 mixed. (There are 792 such cases).
The j loop is looping over all the combinations of 4 (not 5) items from 0:100. There are 100^4 such cases.
The inner loop is looping over all 12 variables, and for those that have a 1 in their bit-position in i, then it means you're using that one. You compute the percentage by taking the next two decimal digits from j. For the 5th item (cnt==5), you don't take digits, you compute it by subtracting from 100.
This will take a LONG time (minutes), but it won't be nearly as bad as 12 nested loops.
for(int a=0;a<=100;a++){
for(int b=0;b<=50;b++){
for(int c=0;c<=34;c++){
for(int d=0;d<=25;d++){
for(int e=0;e<=20;e++){
for(int f=0;f<=17;f++){
for(int g=0;g<=15;g++){
for(int h=0;h<=13;h++){
for(int i=0;i<=12;i++){
for(int j=0;j<=10;j++){
for(int k=0;k<=10;k++){
for(int l=0;l<=9;l++){
if(a+b+c+d+e+f+g+h+i+j+k+l==100)
{
// run 12 for loops for arranging the
// 12 obtained numbers at all 12 places
}}}}}}}}}}}}}
In Original approach(permutation based), the iterations were 102^12 = 1.268e24. Even though the 102th iteration was false, it did check the loop terminating condition for 102th time.
So you had 102^12 condition checks in "for" loops, in addition to "if" condition checks 101^12 times, so in total, 2.4e24 condition checks.
In my solution(combination based),No of for loop checks reduces to 6.243e15 for outer 12 loops, &
if condition checks = 6.243e15.
Now, the no of for loops(ie inner 12 for loops) for every true "if" condition, is 12^12 = 8.9e12.
Let there be x number of true if conditions. so total condition checks
=no of inner for loops*x
= 8.9e12 * x + 6.243e15
I'm not able to find the value of x. however, I believe it wouldnt be large enough to make total conditon checks greater than 2.4e24

Adding integers of array upto some number (java)

I have a java question.
I have two int[] arrays: cdn and cmn.
cdn is {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
cmn is {8,8,16}
I need a program that adds the consecutive integers of cdn[] upto cmn[init] and returns the number of integers used in the addition. Then it continues adding from the next integer of cdn[] upto cmn[init+1] and return the number of integers. For the arrays above this is done 3 times: the first time the return value is 7, the second time it is 7, and the third time it is 16. The number of integers can be collected in and int[] which is {7,7,16}. The code I have is:
int numofints = 0;
int init = 0;
int plus = 0;
while(init < m2){
for(int j = 0; j < cdn.length; j++){
plus += cdn[j];
numofints++;
if(plus == cmn[init]){
init++;
}
}
}
System.out.print(numofints);
in which m2 is the size of cmn, which is 3 in this case. Note that my program starts to loop from the beginning of cdn over and over again, because j = 0. I want it to start where it ended the previous time!
I hope you have a solution for me.
Bjorn
just pull j out of the outer loop, and use a while, instead of for, for the inner loop
and you also need to put plus = 0 into the loop
public class T {
public static void main(String[] args) {
int[] cdn = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] cmn = {8,8,16};
int numofints = 0;
int init = 0;
int m2 = 3;
int j = 0;
while(init < m2){
int plus = 0;
while(j < cdn.length){
plus += cdn[j];
j++;
numofints++;
if(plus == cmn[init]){
init++;
System.out.println(j);
break;
}
}
if (j == cdn.length) break;
}
}
}
Shoudln't if(plus == cmn[init]){ be if(plus >= cmn[init])? If you change cdn at all and "plus" happens to go over "cmn[init]", your code is going to break.

Categories