简体   繁体   English

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

[英]What's wrong in my code (Java character input beginner)

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');
}

} }

I'm just starting to learn Java, can you please tell me what's wrong in my code and how to improve it?我刚开始学习 Java,你能告诉我我的代码有什么问题以及如何改进吗? Thanks谢谢

This is the error I receive.这是我收到的错误。

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)

Think you want to get smth like this:认为你想得到这样的东西:

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');
    }

}

Problems in your implementation:您实施中的问题:

Wrong variable definition错误的变量定义

Attempt to redefine ans variable leads to the compilation error.尝试重新定义ans变量会导致编译错误。 Use different variable names.使用不同的变量名。 For ex:例如:

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

instead of this而不是这个

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

Probably you want to break the loop if answer is correct如果答案正确,您可能想打破循环

So better to add break when ans=='c' :所以最好在ans=='c'时添加 break :

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

While condition variable definition while 条件变量定义

Define redo variable before do-while loop block, otherwise you'll get compilation error在 do-while 循环块之前定义redo变量,否则会出现编译错误

Duplicate local variable "ans" in the following 2 statement.在以下 2 语句中复制局部变量“ans”。 rename anyone of then to another.将当时的任何人重命名为另一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM