Second Occurrence

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

    String statement = "value = alpha*beta + gamma;"  ;
    
    int loc = statement.indexOf( "=");
    if ( loc != -1 )
    {
      String left = statement.substring(  0, loc );
      String right = statement.substring( loc + 1  );
    }

Second Occurrence

Although sometimes correct, it is rare for a line of Java to have two assignment operators in it. Here is a program fragment that inspects a line for this:

String line = "alpha = beta + 23 = 99;" ;

int spot = line.indexOf( "=" );

if (  spot != -1 )
{
  String newLine = line.substring( spot+1 ) ;
  if ( newLine.indexOf("=") > 0  )
  {
    System.out.println( "Possible Bad Line: " + line ); 
  }
}

The statement

  String newLine = line.substring( spot+1 ) ;

computes the tail of the original line, starting with the character after the first = sign. The clause newLine.indexOf("=") > 0 detects = anywhere but at the beginning of this new line (where it would be OK because it would be part of "==").

QUESTION 12:

What if you did not have the startsWith(String str) method? Could you use other methods to replace it?