什么在我的代码是错误的(Java字符输入的初学者)

问题描述:

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字符输入的初学者)

我刚开始学习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) 
+0

为什么你认为之前是怎么回事? –

+0

它不起作用。以下是错误...螺纹 异常“主要” java.lang.Error的:未解决的编译问题: \t重复的局部变量ANS \t SC不能得到解决 \t重复的局部变量重做 \t SC不能得到解决 \t重做无法解析为变量 \t at Application.main(Application.java:9) –

+0

请不要在注释中发布错误。请改编你的问题。 –

想你想获得水木清华这样的:

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

虽然条件变量定义

定义redo可变do-while循环块,否则你会得到编译错误

+0

它导致这个错误.. \t本地变量重做可能没有初始化 –

+0

我已经初始化为零。非常感谢你的帮助 !你知道为什么它应该先设置为零吗? –

+0

如果您检查我的提议中没有break语句的'redo'值,它应该使用某个值(smth而不是'y')进行初始化,否则会打破逻辑。但是,如果在'ans =='c''时使用break语句,比在'redo'检查之前得到循环(所以在这种情况下redo ='0'的定义不是必需的) –

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

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

这个问题中编辑它,并且仍然存在错误 –

+0

@AhmedRefaat将扫描仪更改为Scanner sc。花时间学习如何使用eclipse。这里是一个教程https://www.youtube.com/watch?v = xO5DpU2j-WE – caot

+0

@Ahmed在链接中提供相关问题和示例https://*.com/questions/11871520/how-can-i-read-input-from-the-console-using-the-scanner-class -in-java – caot