Younghak Jang Younghak Jang - 2 months ago 9
Java Question

java error in for loop condition evaluation: not a statement, illegal start of expression

I'm getting errors in the for loop condition statements...
Below is my code.

import static java.lang.Math.*;
import java.util.*;
import java.io.*;

public class p3 {

public static void main(String[] args) {

// input
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();

String result = "1";

for (int j=1; j<num; j++) {
if (checker(result+"1")) result = result+"1";
else if (checker(result+"2")) result = result+"2";
else result = result+"3";
}

System.out.println(result);
}

//checker function
boolean checker(String sr) {
int n = sr.length();

for (int m=1; m<=n/2; m++) {
for (int i=0; i<n-2m+1; i++) {
if (sr.substring(i, i+m) == sr.substring(i+m, i+2m)) {
return false;
}
}
}

return true;
}
}


and below is the error msg. Surely something is wrong with the loop condition in the checker() method, but I can't get it fixed.

p3.java:30: error: ';' expected
for (int i=0; i<n-2m+1; i++) {
^
p3.java:30: error: not a statement
for (int i=0; i<n-2m+1; i++) {
^
p3.java:30: error: ')' expected
for (int i=0; i<n-2m+1; i++) {
^
p3.java:30: error: ';' expected
for (int i=0; i<n-2m+1; i++) {
^
p3.java:31: error: ')' expected
if (sr.substring(i, i+m) == sr.substring(i+m, i+2m)) {
^
p3.java:31: error: illegal start of expression
if (sr.substring(i, i+m) == sr.substring(i+m, i+2m)) {
^
p3.java:31: error: ';' expected
if (sr.substring(i, i+m) == sr.substring(i+m, i+2m)) {
^
7 errors

Answer

A few errors

  for (int i=0; i<n-(2*m)+1; i++) { // use `*`
         // again use `*` also how to compare String - use equals
        if (sr.substring(i, i+m).equals (sr.substring(i+m, i+2 *m))) {  
            return false;
        }
    }

Also the method checker needs to be static as it is being called directly from main

 static boolean checker(String sr) {

Multiply use *

String comparision - use equals