What is wrong with my Java array and methods code?

  • Context: Java 
  • Thread starter Thread starter lypena35
  • Start date Start date
  • Tags Tags
    Array Java
Click For Summary

Discussion Overview

The discussion revolves around troubleshooting Java code related to array manipulation methods. Participants are focused on two specific problems: checking for the presence of a 1 followed by a 2 in an array, and verifying if all elements of one sorted array appear in another sorted array. The scope includes coding errors, method structure, and Java syntax issues.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant identifies that both methods should be declared static to be called from the static main method.
  • Another participant points out that both methods need to return boolean values, not integers.
  • Syntax issues are highlighted, including the need for semicolons at the end of statements and proper formatting of the for loop.
  • Case sensitivity in variable names is noted, with inconsistencies in the use of index variables.
  • Participants discuss the need for proper array indexing to avoid out-of-bounds errors.
  • Errors related to method signatures and argument types are raised, particularly regarding the expected and provided types for method calls.
  • One participant mentions an unclosed curly brace and an extra closing brace in the code structure.
  • Another participant expresses confusion about handling arrays of different lengths in the context of the linearIn method.

Areas of Agreement / Disagreement

Participants generally agree on the need for corrections in the code, but there are multiple competing views on how to resolve specific errors and the best approach to implement the required functionality. The discussion remains unresolved regarding the final implementation of the methods.

Contextual Notes

Limitations include unresolved syntax errors, incorrect method return types, and potential logical flaws in the implementation of the algorithms. The discussion does not reach a consensus on the final code structure or logic.

Who May Find This Useful

Readers interested in Java programming, particularly those dealing with array manipulation and method structuring, may find this discussion beneficial.

lypena35
Messages
18
Reaction score
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
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]
 
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:
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.
 
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;

  }
}
 
According to the assignment, method linearIn should accept two arguments, but the header of the method mentions only one argument.
 
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.
 
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.
 
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!
 

Similar threads

Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
957
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
Replies
4
Views
3K
Replies
2
Views
2K
  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 4 ·
Replies
4
Views
3K