什么';我的代码中有错误(Java字符输入初学者)
} 我刚刚开始学习Java,您能告诉我代码中有什么错误以及如何改进吗?谢谢 这是我收到的错误什么';我的代码中有错误(Java字符输入初学者),java,input,char,Java,Input,Char,} 我刚刚开始学习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
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');
}
在下面的2语句中复制局部变量“ans”。将其中任何一个重命名为另一个
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)
你想得到这样的smth:
Scanner ans = new Scanner(System.in);
char ans = sc.next().charAt(0);
实施中的问题:
变量定义错误
尝试重新定义ans
变量会导致编译错误。使用不同的变量名。例如:
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');
}
}
而不是这个
Scanner scanner = new Scanner(System.in);
char ans = scanner.next().charAt(0);
如果答案正确,您可能希望打破循环
因此,最好在ans=='c'时添加中断:
Scanner ans = new Scanner(System.in);
char ans = sc.next().charAt(0);
而条件变量定义
在do while循环块之前定义
redo
变量,否则您将得到编译错误为什么您认为它是错误的?它不起作用。这里是错误。。。线程“main”java.lang中出现异常。错误:未解决的编译问题:无法解决重复的局部变量ans sc无法解决重复的局部变量redo sc无法解决redo无法在应用程序中解析为变量。main(Application.java:9)请不要在注释中发布错误。请回答你的问题。我已经把我的问题编辑好了。现在您发现这些错误消息的哪一部分不清楚了?@Ahmedreat将Scanner ans更改为Scanner sc。花点时间学习如何使用eclipse。这是一个教程@AhmedRefaat链接中的一个相关问题和示例,它导致了此错误。.局部变量redo可能尚未初始化我已将其初始化为零。非常感谢你的帮助!您知道为什么应该先将其设置为零吗?如果您在我的提案中检查redo
value而不使用break语句,则应该使用一些值(smth而不是'y',否则它会破坏逻辑)。但是如果您在ans=='c'
时使用break语句,那么在检查redo
之前,您将得到循环(因此在这种情况下,redo='0'定义是不必要的)
if (ans == 'c') {
System.out.println("Correct");
break;
}