角色如何增加和减少? (Java)

时间:2018-12-01 12:54:33

标签: java

要求:

如何打印..

  • 前一个字符(例如 a ),
  • 输入的字符和(例如 b
  • 下一个字符? (例如 c

当我输入 b 时,输出应为 a b c

这是我尝试过的 -不幸的是,它不起作用:

import java.util.*;

public class stackoverflow { 
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        char a;
        System.out.println("I have problems in printing statement");
        a = sc.nextcharAt(0);
        System.out.println((a-1)+""+a+""+(a+1));
    }
}

我希望主要的问题出在印刷声明中。预先感谢。

3 个答案:

答案 0 :(得分:1)

您在这里:

 public class stackoverflow {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        char a;
        System.out.println("I have problems in printing statement");
        a = sc.next().charAt(0);
        System.out.println((char)(a - 1) + "" + a + "" + (char)(a + 1));
    }
}

答案 1 :(得分:1)

只需转换为char类型

System.out.println((char) (a - 1) + " " + a + " " + (char) (a + 1));

答案 2 :(得分:1)

您需要稍微更改扫描仪命令并进行正确的类型转换

Scanner sc = new Scanner(System.in);
System.out.print("Enter a letter: ");
int a = (int)sc.next().charAt(0);
System.out.printf("%c %c %c\n", (a-1), a, (a+1));

下面是一个循环,直到用户输入0(零)为止的变体

Scanner sc = new Scanner(System.in);
while (true) {
    System.out.print("Enter a letter (exit with 0): ");
    int a = (int)sc.next().charAt(0);
    if ((char)a == '0') 
        break;
    System.out.printf("%c %c %c\n", (a-1), a, (a+1));
}