Array List Loop Out of Bounds - java

I've got this code which I am developing below. I want to loop through two array lists, the first list I want to look at every entry, the second I only want to look at every 3rd entry and see if they match. If they do match then I want to compare the other two entries on the 2nd list. The problem with the code lies in the "int result1 = " line, I can't understand why it would say out of bounds. Any help much appreciated!
for (int i = 0; i < array1.size(); i++){
for (int j = 3; j <array2.size(); j = j + 3) {
if ((array1.get(i)).equals(array2.get(j-3))){
int result1 = array2.get(j-1).compareTo(array2.get(j-2));
}
}
}

This is an extended comment, not an answer.
It is clear that the posted code cannot produce the stated exception. There is something else going on. You need to prepare a Simple, Self-Contained, Correct Example that produces the exception. Here is an example of a program based on the code you posted that does not reproduce the problem. You need to post something similar, but with enough of your actual code to get the exception.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> array1 = new ArrayList<Integer>();
List<Integer> array2 = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
array1.add(0);
array2.add(0);
}
int result = 0;
for (int i = 0; i < array1.size(); i++) {
for (int j = 3; j < array2.size(); j = j + 3) {
if ((array1.get(i)).equals(array2.get(j - 3))) {
int result1 = array2.get(j - 1).compareTo(array2.get(j - 2));
result += result1;
}
}
}
System.out.println(result);
}
}

Related

How can I complete my code about the Sieve of Erathostenes?

It's about finding the prime numbers from 2 to 1000 using this method but I can't get the solution and I've been thinking and trying to solve this issue for three days. I'm desperate for help so if anyone can help me I would really appreciate it
I tried another for loop and an if statement since my teacher said that I only need another loop or just one more code line but I can't seem to get the solution. I'm really bad at this so I'm sorry if my code seems cringeworthy
public class Practica {
public static void main(String []
byte []marcado = new byte [1000];
for (int i = 2; i < 1000; i++);
if (marcado[i] == 1) {
for (int j = 2; i*j < 1000; j++) {
marcado [i*j] = 0;
}
}
I expect to have all the prime numbers printed
Give it a shot:
public static void main(String[] args) {
byte[] marcado = new byte[1000];
for (int i = 2; i*i < 1000; i++) {
if (marcado[i] == 0) {
for (int j = 2; i * j < 1000; j++) {
marcado[i * j] = 1;
}
}
}
// print the numbers:
for (int i = 1; i < 1000; i++) {
if(0 == marcado[i]){
System.out.print(" " + i);
}
}
}
Besides removing syntax errors, I reversed the logic such that marcado[i]==0 indicates a prime and noneprime otherwise.
The other possibility based on your aproach would be to initialize all the array elements with "1"(eg. with fill);

Take a word and print it out in the shape of a triangle as shown below - Parameters and methods

Thanks for taking the time to check out my question. I have to write some code in Dr. Java that takes in a word and then prints it out in a specific pattern. Basically here are some examples:
Input: fishy
Output: f
fifi
fisfisfis
fishfishfishfish
fishyfishyfishyfishyfishy
Basically, I'm just adding another character to the previous one and printing it out that many number of times.
Here is my attempt at my solution:
String wordcopy = word;
int size = wordcopy.length();
for (int i=1; i<=size; i+=1)
{
for (int j=0; j<i; j++)
{
System.out.print(word.substring(0,j+1));
}
System.out.println("");
}}
I have already set up my parameters so that's fine. The only thing I seem to be missing is the method itself that prints out what it's supposed to. Can anyone please help me with this problem and how I can go from here?
Thanks!
Replace word.substring(0,j+1) with word.substring(0,i):
String wordcopy = word;
int size = wordcopy.length();
for (int i = 1; i <= size; i += 1) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}
There are some cleanup things you can do. For instance, this code yields the same result:
for (int i = 1; i <= word.length(); i++) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}

ComparisonCountingSort pseudocode difficulty

This algorithm given to us in class:
I am having trouble in my attempts to determine the output when the input is an array A[60,35,81,98,14,47].
I wanted to get used to the pseudocode syntax, so I tried to convert this to Java syntax, but the resulting program won't show a result. This is my converted code:
public class Driver
{
public static void main(String[] args)
{
int[] test = {60, 35, 81, 98, 14, 47};
int[] converse = new int[6];
converse = countSort(test);
for(int i : converse)
{
System.out.println(converse[i]);
}
}
public static int[] countSort(int[] a)
{
int[] s = new int[6];
int[] count = new int[6];
int n = a.length + 1;
for(int i = 0; i < (n-1);)
{
count[i] = 0;
}
for(int i = 0; i < (n-2);)
{
for(int j = (i+1); i < (n-1);)
{
if(a[i] < a[j])
{
count[j] = count[j]+1;//What
}
else
{
count[i] = count[i]+1;
}
}
}
for (int i = 0; i < (n-1);)
{
s[count[i]] = a[i];
}
return s;
}
}
int[] test = {60,35,81,98,14,47}; is never used.
Did you mean to pass test into countSort? and also do something with it's result.
While I haven't looked at the algorithm really, there is something else wrong here:
int n = a.length + 1;
for (int i = 0; i < (n - 1);) {
count[i] = 0;
}
This will loop indefinatetly. i never incerements.
Your array test is never used.
In your for loops, i never gets incremented. It will loop infinetely.
Instead of n = a.length+1; just use n = a.length. it makes your code easier to read. You then also have to check all your loops.
When you are running the code with a testset larger or less than 6 integer values your code wont run correctly or even fail with an ArrayOutOfBounds Exception, as you allocate the arrays s and count for only 6 values.
Try int[] count = new int[a.length]; instead of int[] count = new int[a.length];. The same for s.

I need to sort through an object array and order them highest to lowest

I am a student in a beginning java class, I got some help earlier today on my assignment, which really helped! So I thought I would give it one more try, before I throw in the towel on this last part. I have been able to get everything going, but my sort just doesn't work. I have to use this format, as my professor does not want us to use sort APIs. It processes correctly, meaning I get the same results by hand as when I run it, so I think the problem is in the logic itself. Can anyone see what I am doing wrong and offer any hints or helps. Thanks in advance. Here is my code for my sort loop:
int i, j; // used to index into the array
double temp;
for (i = 1; i < count ; ++i) {
temp = students[i].getGPA();
j = i - 1;
while (j >= 0 && temp < students[j].getGPA())
{
students[j + 1] = students[j];
j = j - 1;
}
students[j + 1]= students[i];
}
Your are not doing the swapping correctly. Check this sample code:
for (int i = 0; i < students.length; i++)
{
for (int j = 1; j < students.length - i; j++)
{
if (students[j - 1].getGPA() > students[j].getGPA())
{
// assuming that your class name is Student
Student temp = students[j - 1];
students[j - 1] = students[j];
students[j] = temp;
}
}
}
Your problem is that the first iteration through the while loop overwrites students[i]. You need to keep students[i], and not just its GPA, in a temporary value when you enter the for loop.
Refined your logic little bit. Plz verify for appropriateness!
package com.kvvssut.misc;
public class SortArray {
public static void main(String[] args) {
double [] studentsGPA = {8.3,7.2,10,6.5,4.9};
int count = studentsGPA.length;
int i, j; // used to index into the array
double temp;
for (i = 1; i < count ; ++i) {
j = i;
while (j > 0 && (temp = studentsGPA[j]) < studentsGPA[--j]) { // can use students[j].getGPA() similarly
studentsGPA[j+1] = studentsGPA[j];
studentsGPA[j] = temp;
}
}
for (double sgpa : studentsGPA ) {
System.out.println(sgpa);
}
}
}

ArrayList of ArrayLists - clear function confusion

Here is a particular method I have written:
class A {
private static ArrayList<ArrayList<Integer>> inputTerms = new ArrayList<ArrayList<Integer>();
public static void method1(ArrayList<Integer> terms) {
ArrayList<Integer> clauses = new ArrayList<Integer>();
int N = terms.size();
for (int i = 0; i < N - 1; i++) {
for (int j = i + 1; j < N; j++) {
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
clauses.clear();
}
}
}
}
This method is called multiple times from the main function.
In the end, i try to write the contents of the class variable into a file. However, when I do this, i get 0 as the contents of inputTerms. However, if i remove the clauses.clear() line, i am able to get approppriate values.
My program is such that it is vital for me to clear the clauses after adding to inputTerms. Is there any alternative to this?
**Hmmm.. I have done what you've suggested. However, I haven't quite overcome the problem. To give more background, in my main function, I have the following code:
for (int i=0; i<N-1; i++){
ArrayList<Integer> firstdiagonalTerms = new ArrayList<Integer>();
for (int j=0; j<N-i; j++){
firstdiagonalTerms.add(variable[j][i+j]);
}
method1(firstdiagonalTerms);
}
I have to call the method1 function 4 times for different combinations of 'i' and 'j'. However, I still get 0 when I use the above mentioned suggestions**
You are adding the same list and clearing it repeatedly. When you add an object to a list it copies a reference to it, not a copy of the object.
int N = terms.size();
for (int i = 0; i < N - 1; i++) {
for (int j = i + 1; j < N; j++) {
List<Integer> clauses = new ArrayList<Integer>();
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
}
}
or
for (int i = 0, N = terms.size(); i < N - 1; i++)
for (int j = i + 1; j < N; j++)
inputTerms.add(Arrays.asList(-terms.get(i), -terms.get(j)));
Not sure i understand what you are trying to achieve, but you keep reusing the same list, which is probably not what you meant to do.
You should probably move the ArrayList<Integer> clauses = new ArrayList<Integer>(); inside the inner loop, and not call clauses.clear() at all.
When you are adding "clauses" you are adding the actual object to the arrayList, not a copy. So when you clear them all the values in the list will be removed. To get arround this, add a clone of the list:
inputTerms.add((ArrayList<Integer>) clauses.clone());
When you call clear() on list, you are updating/removing same objects (because list contains reference to objects, not copy of object). That is what causing the issue.
I think you need to do something like below. Instead of using clear(), create a new list everytime.
public static void method1 (ArrayList<Integer> terms)
{
int N = terms.size();
for (int i = 0; i<N-1; i++) {
for (int j=i+1; j<N; j++) {
ArrayList<Integer> clauses = new ArrayList<Integer>();
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
}
}

Categories