无法编译我的代码

时间:2012-10-05 06:01:09

标签: java string compiler-errors

我想打印这个标志/\但是在编译器上,我认为一切都很好,但无法编译。错误显示为

leets.java:13: error: unclosed string literal
System.out.printf ("%s /\",ch);
                     ^
 leets.java:13: error: ';' expected
 System.out.printf ("%s /\",ch);
                     ^
 2 errors

我的代码如下。

import java.util.Scanner;
public class switchDemo2
{
    public static void main ( String args[] )
    {
    Scanner i = new Scanner ( System.in );
    System.out.print ( "Enter a character to test: " );
    char ch;
    ch = i.next().charAt(0);
    switch ( ch )
    {
    case 'A': case 'a':
    System.out.printf ("%s /\",ch);
                       break;
    case 'B': case 'b':
        System.out.printf ("%s 13",ch);
    break;
    case 'C': case 'c':
    System.out.printf ("%s )",ch);
    break;
    case 'D': case 'd':
    System.out.printf ("%s 1)",ch);
    break;
    case 'E': case 'e':
    System.out.printf ("%s 3",ch);
    break;
    case 'F': case 'f':
    System.out.printf ("%s 1=",ch);
    break;
    default:
    System.out.printf ("%s not a lowercase vowel\n",ch);
}
}

4 个答案:

答案 0 :(得分:4)

你需要将反斜杠转义为。

 System.out.printf ("%c /\\",ch);

您可以看到有关它的更多信息here

很少有评论:

  1. 您使用"%s"表示字符,可以使用"%c表示字符。请参阅格式tutorial
  2. 您没有关闭扫描仪,您会收到警告。您应该使用Scanner.close()方法关闭它。
  3. 剩下的最后一个大括号}

答案 1 :(得分:1)

System.out.printf ("%s /\\",ch);

而不是System.out.printf ("%s /\",ch);

 Escape Sequence    Description
 \t     Insert a tab in the text at this point.
 \b     Insert a backspace in the text at this point.
 \n     Insert a newline in the text at this point.
 \r     Insert a carriage return in the text at this point.
 \f     Insert a formfeed in the text at this point.
 \'     Insert a single quote character in the text at this point.
 \"     Insert a double quote character in the text at this point.
 \\     Insert a backslash character in the text at this point

Here is the Tutorial on characters in java

答案 2 :(得分:0)

需要转义反斜杠: -

System.out.printf ("%c /\\",ch);

您可以将: - switch ( ch )更改为switch(Character.toLowerCase(ch)),以避免同时包含Aa的案例。只需使用case 'a':

即可

答案 3 :(得分:0)

这对你有用;

System.out.printf(“%s'/ \\'”,ch);

此致

Dinuka