2

I am new to java and I am supposed to get an output like the following:

Type in your first name: John

Hi, "John"
The name of this exercise is 'Modifying printing'.
Tabulator, line change and quotations have already been used in this exercise.
Backward slash (\) is also usable in printing.

End of exercise

But I couldn't get the name part, John, within " ". Please any one help me. My code looks as follows:


import java.util.Scanner;
public class apples {
public static void main(String[] args) {
String s;
String m;
Scanner reader= new Scanner(System.in);
System.out.print("Type in your first name: ");
s= reader.nextLine();
m="Forward slash (\\) is also usable in printing.";
System.out.println();
System.out.println();
System.out.println("Hi, "+s);
System.out.println("\tThe name of this exercise is 'Modifying printing'.");
System.out.println("\tTabulator, line change and quotations have already been used in   this exercise.");
System.out.println("\t"+m);
System.out.println();
System.out.println();
System.out.println("\t\t*** End of exercise ***");
}
}

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
user3314727
  • 17
  • 1
  • 4

4 Answers4

1

Use the escape character \:

System.out.println(String.format("Hi, \"%s\"",s));
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1
 System.out.println("Hi, \"" + s + "\"");

where \ is used to escape the following ".

search for "escaping characters in java" in your favourite search engine.

Have fun getting started with Java!

donfuxx
  • 11,277
  • 6
  • 44
  • 76
  • No problem! In fact you already escaped a char in your code! Check the line `m="Forward slash (\\) is also usable in printing.";` ;-) – donfuxx Feb 16 '14 at 00:01
  • @user3314727 this question still appears as unresolved. could you please mark it as resolved? – donfuxx Feb 22 '14 at 07:59
0

When you want to insert a " character in a string, you have to prepend a \ to mark it as non-string-terminating.

Smutje
  • 17,733
  • 4
  • 24
  • 41
0

You have to escape the ".

To do that you use the \ character.

So if you want to print Hello "John", you could do System.out.println("Hello \"John\"");

xp500
  • 1,426
  • 7
  • 11