Learn Programming in Java


<<Previous | ToC | Next >>

Seaman

Again we start with an existing English program. If you saved yours, use it. Otherwise here is mine:
Let theWord = ""
Let guessWd = ""
Let nLets = 0
Let sofar = 0
Let nerrs = 0
Repeat
  Input letter 1
  If letter < "A" then Exit
  Let theWord = theWord # letter
  Let guessWd = guessWd # "_"
  Add 1 to nLets
  Next
print "[Got '" theWord "']"
Repeat 33 {to clear screen}
  Print " "
  Next
Repeat
  Print guessWd " e=" nerrs
  if nerrs>5 exit
  if sofar=nLets exit
  Input letter,1
  Let nuly = ""
  Let offs = 0
  Let seen = 0
  Repeat nLets
    Character looky = theWord,offs
    Character prio = guessWd,offs
    Add 1 to offs
    if looky=letter then Add 1 to seen
      Otherwise Let looky = prio
    Let nuly = nuly # looky
    Next
  Let guessWd = nuly
  If seen>0 then add seen to sofar {score match}
  If seen=0 then add 1 to nerrs {score no-match}
  Next
if nerrs>6 print "Too bad"
if sofar=nLets print "You got it"


You recall, we picked letters out of a single word variable in English, because English has no such thing as arrays. Java has arrays, and we will use them.

So instead of declaring theWord and gw as String, we will declare them as

char[] theWord = new char[64];
char[] guessWd = new char[64];
Do you think 64 is enough? Google tells me there are a few English words longer than 40, but only one of each size, so if your player picks one of those, the other person would know immediately (after consulting Google) which word it is.

Instead of building these words by concatenation ('#' in English above), we can simple set the designated array element (letter) to the appropriate value:

theWord[nLets] = letter;
guessWd[nLets] = '_';
Notice that character constants in Java use apostrophes (single quotes) while String constants use double quotes. These are character (char) arrays, not strings.

Extracting those same letters is as simple as using the array reference:

looky = theWord[offs];
prio = guessWd[offs];
and you can put characters back into the array without rebuilding a whole other word to recopy:
guessWd[offs] = looky;


OK, do you think you can do the rest? Make it work in Java, then we'll look at the different ways to do ASCII Graphics.

Next: ASCII Graphics

<<Previous | ToC | Next >>

Revised: 2021 August 28