我的代码有什么问题(Java字符输入初学者)

时间:2017-09-24 20:59:45

标签: java input char

import java.util.Scanner;
public class Application {

public static void main(String[] args) {
    do {
    System.out.println("What is the command keyword to exit a loop in Java?\na. int\nb. continue\nc. break\nd. exit\nEnter your choice");
    Scanner ans = new Scanner(System.in);
    char ans = sc.next().charAt(0);
    if(ans=='c')
        System.out.println("Correct");
    else
        System.out.println("Wrong! Presss Y to try again.");
    Scanner redo = new Scanner(System.in);
    char redo = sc.next().charAt(0);
    }
    while(redo=='y');
}

}

我刚刚开始学习Java,你能否告诉我我的代码有什么问题以及如何改进它?感谢

这是我收到的错误。

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Duplicate local variable ans
sc cannot be resolved
Duplicate local variable redo
sc cannot be resolved
redo cannot be resolved to a variable

at Application.main(Application.java:9)

2 个答案:

答案 0 :(得分:1)

认为你想得到像这样的东西:

public class Application {

    public static void main(String[] args) {
        char redo;
        do {
            System.out.println("What is the command keyword to exit a loop in Java?\na. int\nb. continue\nc. break\nd. exit\nEnter your choice");
            Scanner scanner = new Scanner(System.in);
            char ans = scanner.next().charAt(0);
            if (ans == 'c') {
                System.out.println("Correct");
                break;
            }
            else {
                System.out.println("Wrong! Presss Y to try again.");
                redo = scanner.next().charAt(0);
            }
        }
        while (redo == 'y');
    }

}

实施中的问题:

错误的变量定义

尝试重新定义ans变量会导致编译错误。使用不同的变量名称。例如:

Scanner scanner = new Scanner(System.in);
char ans = scanner.next().charAt(0);

而不是

Scanner ans = new Scanner(System.in);
char ans = sc.next().charAt(0);

如果答案正确,您可能想要打破循环

最好在ans=='c'时添加中断:

if (ans == 'c') {
   System.out.println("Correct");
   break;
}

条件变量定义

在do-while循环块之前定义redo变量,否则会出现编译错误

答案 1 :(得分:0)

在以下2个语句中复制局部变量“ans”。将任何人重命名为另一人。

Scanner ans = new Scanner(System.in);
   char ans = sc.next().charAt(0);