2

So for my Introduction to Java class, I am suppose to create a gingerbread man with ASCII. This is the very first assignment, so the class has only covered only println statments so far. I'm using the Eclipse IDE for Java Developers on OSX 64-bit.

This is what I have right now:

import acm.program.*;

public class ASCIIArtProgram extends ConsoleProgram {

    public void run() {
        println("   _   ");
        println(" _(")_ ");
        println("(_ . _)");
        println(" / : \ ");
        println("(_/ \_)");
    }

}

Some reason I'm getting errors on line 7. It keeps changing the semi-colon into a colon.

Errors:

  • Syntax error on token "_", invalid AssignmentOperator

  • String literal is not properly closed by a double-quote

The program is suppose to output this:

   _
 _(")_
(_ . _)
 / : \
(_/ \_)

I'm confused what I'm doing wrong.

John
  • 29
  • 1
  • 3
  • 1
    You need to read more on Java basics. Please refer to "escape characters". Check this page here [link](http://docs.oracle.com/javase/tutorial/java/data/characters.html) – Aditya K Oct 02 '14 at 06:59
  • @MeenaO - Checkout this Q&A. – jww Aug 30 '18 at 01:48

4 Answers4

5

Where you have

println(" _(")_ ");
            ^

the quote inside your string is terminating the string. That is how quoted strings work. If you want to print a quote inside a string, you need to have

println(" _(\")_ ");

You will also find that you need to replace your printed \ with \\ as well, since \ on its own has the special meaning of "escape the next character".

i.e.

public void run() {
    println("   _   ");
    println(" _(\")_ ");
    println("(_ . _)");
    println(" / : \\ ");
    println("(_/ \\_)");
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
2

You have to escape special characters you want to print, because the compiler doesn't know, if your " means print " or start/stop a String. Same goes for \.

To escape a character, simply write a \ infront of it. So:

  • " becomes \"
  • \ becomes \\

You can read more about characters and escaping in the Java Tutorials from Oracle.

ifloop
  • 8,079
  • 2
  • 26
  • 35
1

Take a closer look at...

println(" _(")_ ");
        ^---^---^

You open, close and open the quotes, " _(" is a proper String literal, )_ " is garbage as far as the compiler is concerned, as it's not any valid Java command it can interpret.

You need to escape the second quote, for example...

println(" _(\")_ ");

This will make Java ignore it and treat it as (literally) as part of the Strings content...

The \ also has special meaning, as you've seen, you also need to escape it...

println(" / : \\ ");
println("(_/ \\_)");
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You need to quote the back slashes

use \\ instead of \ in your strings

thus:

println(" / : \\ ");

here a list of all chars you will have to escape/quote when you want to use them in a string literal

Community
  • 1
  • 1
A4L
  • 17,353
  • 6
  • 49
  • 70