What is wrong with my Java array and methods code?

  • Java
  • Thread starter lypena35
  • Start date
  • Tags
    Array Java
In summary, the problem is that you are missing a semicolon at the end of the for statement in line 44.
  • #1
lypena35
18
0
Hello,

I am stuck on this java problem. I was wondering if anyone can figure out what I am doing wrong. Thank you!

Problem
1. Given an array of ints, return true if there is a 1 in the array with a 2 somewhere later in the array.

ex: has12([1, 3, 2]) → true
has12([3, 1, 2]) → true
has12([3, 1, 4, 5, 2]) → true

2. Given two arrays of ints sorted in increasing order, outer and inner, return true if all of the numbers in inner appear in outer. The best solution makes only a single "linear" pass of both arrays, taking advantage of the fact that both arrays are already in sorted order.
ex:
linearIn([1, 2, 4, 6], [2, 4]) → true
linearIn([1, 2, 4, 6], [2, 3, 4]) → false
linearIn([1, 2, 4, 4, 6], [2, 4]) → true

My Code.

Code:
public class ArrayProblems{
  public static void main(){
    int[] a = {1,3,2};
    int[] b = {3,1,2};
    int[] c = {3,1,4,5};
    int[] d = {1,2,4,6};
    int[] e = {1,2,4,4,6};
    int[] f = {2,4};
    int[] g = {2,3,4};

    boolean test1 = has12(a);
    boolean test2 = has12(b);
    boolean test3 = has12(c);

    System.out.println("Test 1: " + test1); //should print true
    System.out.println("Test 2: " + test2); //should print true
    System.out.println("Test 3: " + test3); //should print false
    System.out.println("Test 4: " + lieanrIn(d,f)); //should print true
    System.out.println("Test 5: " + lieanrIn(d,g)); //should print false
    System.out.println("Test 6: " + lieanrIn(e,f)); //should print true

  }

 [U] //has12 method goes here[/U]

public int has12(int[]array){
int indexOf1=0;
int indexOf2=0;
int i=0;
int j=0;

for( i=0,i<=array.length,i++){
if (array[i]==1){
indexof1=i;
break
}
}
if (i== array.length){
return false;
}
for(i=indexOf1+1<=array.length){
if (array[i]==1){
idexof2=i;
break
}
}
if(i==array.length){
return false;
}
if(indexOf1<indexof2){
return true;
}

//linearIn method goes here

Code:
public int linearIn(int[]a,int[]b){
for(i=0, i<b.length,i++){
for(i=0,i<a.length,i++){
if(a[j]==b[i]){
i=i+1;
}
if(j==a.length){
return false;
}
}
}
return true;

}
}
}
 
Technology news on Phys.org
  • #2
I'll mostly focus on method has12.

1. Both methods you have to write should be declared static. This means they pertain to the class ArrayProblems as a whole and not to any of its objects. Both methods are called from the static method [m]main()[/m], which is called before any object of ArrayProblems is created. Therefore, your method similarly should work when no objects of the main class exist.

2. Both methods should return true or false, i.e., values of type [m]boolean[/m].

3. Operators [m]break[/m], just line any operator, need to end with semicolons.

4. The syntax for the [m]for[/m] operator is

[m]for (initialization; condition; update) { ... }[/m]

In particular, the three parts are separated by semicolons. Each of the three parts can have multiple subparts separated by commas (e.g., you may have two assignments [m]i++, j++[/m] in the update section of [m]for[/m]), but this is a subtlety that you can skip for now.

5. You sometimes use [m]indexOf1[/m] and sometimes [m]indexof1[/m], and similarly for [m]indexOf2[/m]. Identifiers in Java are case-sensitive.

6. The array index in the loop should vary between 0 and [m]array.length-1[/m], inclusive. The index [m]array.length[/m] is already out of bounds. Therefore the condition in [m]for[/m] should check for [m]i < array.length[/m] and not [m]i <= array.length[/m].

7. The second [m]for[/m] is strange. First, the header inside parentheses does not have the three parts described above separated by semicolons. Second, you are searching for 1 instead of 2. The variable [m]indexOf2[/m] is spelled incorrectly.

8. The [m]main(String[] args)[/m] should have the argument shown. It's the array containing the command-line arguments of the program.

9. Any method that has a return type other than [m]void[/m] must have a return statement, which clearly executes from the standpoint of the compiler. In your code the last return statement is wrapped in [m]if[/m]. The compiler does not know that the condition of this [m]if[/m] will always be true, so from the standpoint of the compiler, this return statement may sometimes be skipped. It seems that the last [m]if[/m] is unnecessary, and therefore so is the variable [m]indexOf2[/m].

10. Instead of

[m]if (i == array.length) return false; else return true;[/m]

you can say

[m]return (i < array.length);[/m]
 
  • #3
Ok so I cleaned up my code. Now when I try to compile it returns these errors and I don't understand why, I tried to fix the curly brackets and I tried to fix the arguments still no luck. My new code is below.

Code:
ArrayProblems1.java:44: error: illegal start of expression
  public static int linearIn(int[] array) {
  ^
ArrayProblems1.java:44: error: illegal start of expression
  public static int linearIn(int[] array) {
         ^
ArrayProblems1.java:44: error: ';' expected
  public static int linearIn(int[] array) {
               ^
ArrayProblems1.java:44: error: '.class' expected
  public static int linearIn(int[] array) {
                                   ^
ArrayProblems1.java:44: error: ';' expected
  public static int linearIn(int[] array) {
                                        ^
5 errors

Code:
public class ArrayProblems1 {
 public static void main(String[] args) {
  int[] a = {1,3,2};
  int[] b = {3,1,2};
  int[] c = {3,1,4,5};
  int[] d = {1,2,4,6};
  int[] e = {1,2,4,4,6};
  int[] f = {2,4};
  int[] g = {2,3,4};

  boolean test1 = has12(a);
  boolean test2 = has12(b);
  boolean test3 = has12(c);

  System.out.println("Test 1: " + test1); //should print true
  System.out.println("Test 2: " + test2); //should print true
  System.out.println("Test 3: " + test3); //should print false
  System.out.println("Test 4: " + lieanrIn(d, f)); //should print true
  System.out.println("Test 5: " + lieanrIn(d, g)); //should print false
  System.out.println("Test 6: " + lieanrIn(e, f)); //should print true

 }

 //has12 method goes here

 public static int has12(int[] array) {
  int i;
  int j;
  int x;

  for(x=0;x<array.length;x++){
      if(array[x]==1){
      }
    for(i=0;i<array[i];i++){
        if (array[i]==2){
            return true;
        }
        else{
            return false;
        }
    }      
  }
  //linearIn method goes here
  public static int linearIn(int[] array) {
   for (i = 0; i < array.length; i++) {
    for (j = 0; i < array.length; j++) {
     if (array[j] == array[i]) {
      i = i + 1;
     }
     if (j ==array.length) {
      return false;
     }
    }
   }
   return true;

  }
 }
}
 
Last edited by a moderator:
  • #4
There is an unclosed curly brace after method has12, but an extra closing brace after method linearIn. Also, you have not addressed by remark 2 from post #2: both methods should have [m]boolean[/m] as their return types. Please use the [CODE]...[/CODE] tags for code because it preserves formatting.
 
  • #5
Oh ok. Opps sorry I went ahead and fixed it but my compiler (Terminal) doesn't like the fact that the arrays are different lengths. Since the problem requires this What should I do?

Code:
ArrayProblems1.java:18: error: method linearIn in class ArrayProblems1 cannot be applied to given types;
  System.out.println("Test 4: " + linearIn(d, f)); //should print true
                                  ^
  required: int[]
  found: int[],int[]
  reason: actual and formal argument lists differ in length
ArrayProblems1.java:19: error: method linearIn in class ArrayProblems1 cannot be applied to given types;
  System.out.println("Test 5: " + linearIn(d, g)); //should print false
                                  ^
  required: int[]
  found: int[],int[]
  reason: actual and formal argument lists differ in length
ArrayProblems1.java:20: error: method linearIn in class ArrayProblems1 cannot be applied to given types;
  System.out.println("Test 6: " + linearIn(e, f)); //should print true
                                  ^
  required: int[]
  found: int[],int[]
  reason: actual and formal argument lists differ in length
3 errors
MyCode.
Code:
public class ArrayProblems1 {
 public static void main(String[] args) {
  int[] a = {1,3,2};
  int[] b = {3,1,2};
  int[] c = {3,1,4,5};
  int[] d = {1,2,4,6};
  int[] e = {1,2,4,4,6};
  int[] f = {2,4};
  int[] g = {2,3,4};

  boolean test1 = has12(a);
  boolean test2 = has12(b);
  boolean test3 = has12(c);

  System.out.println("Test 1: " + test1); //should print true
  System.out.println("Test 2: " + test2); //should print true
  System.out.println("Test 3: " + test3); //should print false
  System.out.println("Test 4: " + linearIn(d, f)); //should print true
  System.out.println("Test 5: " + linearIn(d, g)); //should print false
  System.out.println("Test 6: " + linearIn(e, f)); //should print true

 }

 //has12 method goes here

 public static boolean has12(int[] array) {
  int i;
  int x;

  for(x=0;x<array.length;x++){
      if(array[x]==1){
      }
    for(i=0;i<array[i];i++){
        if (array[i]==2){
            return true;
        }
        else{
            return false;
        }
    }      
  }
 }
  //linearIn method goes here
  public static boolean linearIn(int[] array) {
      int i;
      int j;
   for (i = 0; i < array.length; i++) {
    for (j = 0; j < array.length; j++) {
     if (array[j] == array[i]) {
      i = i + 1;
     }
     if (j ==array.length) {
      return false;
     }
    }
   }
   return true;

  }
}
 
  • #6
According to the assignment, method linearIn should accept two arguments, but the header of the method mentions only one argument.
 
  • #7
Oh ok how do I do that? I tried adding another int[] array but it said it was already defined, then I tried int[] int[] array, and int[][] array, none of which worked. We didn't go over this stuff in class so I am confused I am sorry.
 
  • #8
lypena35 said:
Oh ok how do I do that? I tried adding another int[] array but it said it was already defined
You should post the complete code or the relevant fragment. "Adding another int[] array" does not provide enough information.

The header of linearIn method should be

[m]public static boolean linearIn(int[] outer, int[] inner) {[/m]

lypena35 said:
I tried int[] int[] array, and int[][] array, none of which worked.
Trying different syntax variants is the last thing you should do. A more productive way to spend time is reading lecture notes or a textbook. There are many books on Java.
 
  • #9
Ok, Thank you very much for your help I appreciate it. I will look for a supplemental book.
 
Last edited:
  • #10
One more question.

I keep getting the wrong return values:
Terminal Output
Code:
Test 1: false// should be true
Test 2: false//should be true
Test 3: false
Test 4: true
Test 5: true//should be false
Test 6: true

MyCode
Code:
public class ArrayProblems1 {
 public static void main(String[] args) {
  int[] a = {1,3,2};
  int[] b = {3,1,2};
  int[] c = {3,1,4,5};
  int[] d = {1,2,4,6};
  int[] e = {1,2,4,4,6};
  int[] f = {2,4};
  int[] g = {2,3,4};

  boolean test1 = has12(a);
  boolean test2 = has12(b);
  boolean test3 = has12(c);

  System.out.println("Test 1: " + test1); //should print true
  System.out.println("Test 2: " + test2); //should print true
  System.out.println("Test 3: " + test3); //should print false
  System.out.println("Test 4: " + linearIn(d, f)); //should print true
  System.out.println("Test 5: " + linearIn(d, g)); //should print false
  System.out.println("Test 6: " + linearIn(e, f)); //should print true

 }

 //has12 method goes here

 public static boolean has12(int[] array) {
  int i;
  int x;

  for(x=0;x<array.length;x++){
      if(array[x]==1){
      }
    for(i=0;i<array[i];i++){
        if (array[i]==2){
            return true;
        }
    }      
  }
     return false;
 }
  //linearIn method goes here
  public static boolean linearIn(int[] outer, int[] inner) {
      int i;
      int j;
   for (i = 0; i < inner.length; i++) {
    for (j = 0; j < outer.length; j++) {
     if (outer[j] == inner[i]) {
      i = i + 1;
     }
     if (j ==inner.length) {
      return true;
     }
    }
   }
   return false;

  }
}
 
  • #11
There are numerous logical problems with your code. The operator

[m]if(array[x]==1) {}[/m]

is never necessary. It checks the condition, but does not do anything if it holds. {} denotes the empty operator, or do-nothing instruction. Perhaps you mean the following.

Code:
  public static boolean has12(int[] array) {
    int i;
    int x;

    for (x = 0; x < array.length; x++) {
      if (array[x] == 1) {
        for (i = x + 1; i < array.length; i++) {
          if (array[i] == 2) return true;
        }
      }
    }
    return false;
  }
 
  • #12
The second half because it is asking something different will not return false even if the same modifications are made. I tried taking out the if statements and neither worked in doing so. Therefore, test 5 still won't return false. What do I do?

terminal output
Code:
Test 1: true
Test 2: true
Test 3: false
Test 4: true
Test 5: true//needs to be false
Test 6: true

My Code
Code:
//linearIn method goes here
  public static boolean linearIn(int[] outer, int[] inner) {
      int i;
      int j;
   for (i = 0; i < inner.length; i++) {
    for (j = i+1; j < outer.length; j++) {
     if (outer[j] == inner[i]) {
      
     }
     if (j ==inner.length) return true;
     
    }
   }
   return false;
 
  • #13
I already said that [m]if (outer[j] == inner) {}[/m] is useless because {} denotes a no-op.

Your algorithms is in general incorrect. It may help you to come up with a correct algorithm if you study the examples and pretend that you have two pointers (fingers). In the beginning the pointers point to the first elements of both arrays. Now you need to figure out how to move the pointers to check whether the second array is contained in the first one.
 
  • #14
You are absolutely right. That was a perfect example to help me put things into perspective. It is working now thank you!
 

FAQ: What is wrong with my Java array and methods code?

What is a Java array?

A Java array is a data structure that allows you to store a collection of values of the same type. It is a fixed-sized container that can hold multiple elements, and each element can be accessed using its index.

How do I declare an array in Java?

To declare an array in Java, you need to specify the type of elements it will hold, followed by square brackets and the name of the array. For example, to declare an array of integers called "numbers", you would write: "int[] numbers;"

What is the difference between a one-dimensional and multidimensional array in Java?

A one-dimensional array is a simple list of elements, while a multidimensional array is an array of arrays. In other words, a one-dimensional array has only one index or dimension, while a multidimensional array has multiple indexes or dimensions to access its elements.

How do I access and modify elements in a Java array?

You can access and modify elements in a Java array using their index. The index starts at 0, so the first element in an array can be accessed using index 0. To modify an element, you can simply assign a new value to it using its index. For example, "numbers[0] = 10;" would change the first element in the "numbers" array to 10.

What are methods in Java and how can they be used with arrays?

In Java, methods are blocks of code that perform a specific task. They can be used with arrays to manipulate the array's elements or perform operations on the array. For example, you can create a method to find the sum of all elements in an array or to sort the elements in an array. This allows for code reusability and makes working with arrays more efficient.

Back
Top