所以,我学习Java已经两天了,在编译下面的代码时遇到了一条错误消息。我试图做的是一个简单的程序,该程序从系统输入中获取名称,然后想要知道该名称是否为您想要使用的名称。工作完美。因此,我想对其进行修改:如果这不是所需的名称,则您应该能够根据需要多次输入该名称。这就是为什么我在其中具有布尔值“ confirmed”以及while循环的原因。编译后,即使我明确声明并使用了布尔值,我也会收到“已确认”布尔值的错误消息“未使用确定的局部变量的值”。我试过简单地移动初始声明,它没有任何改变。有人知道如何解决该问题或重新执行我的循环,这样就不会有任何问题吗?
Fyi,我正在将VS Code与Java扩展包一起使用。
import java.util.*;
public class Name{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
try{
boolean confirmed = false;
while(confirmed = false){
System.out.println("What's your name again?");
String enteredName = sc.nextLine();
System.out.println("So, your name is " + enteredName + "?\nEnter 'yes' to confirm or 'no' to type a new name.");
String confirmation = sc.nextLine();
if(confirmation.equalsIgnoreCase("yes") || confirmation.equalsIgnoreCase("yes.")){
System.out.println("Confirmed, " + enteredName + ".\n\nNow launching.");
confirmed = true;
}
else if(confirmation.equalsIgnoreCase("no") || confirmation.equalsIgnoreCase("no.")){
System.out.println("Please enter a new name.");
confirmed = false;
}
}
}
finally{
sc.close();
}
}
}
您不应该为Scanner
关闭System.in
,因为它也会关闭System.in
。除此之外,您可以如下简化代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String confirmation, enteredName;
do {
System.out.print("What's your name again?");
enteredName = sc.nextLine();
System.out
.print("So, your name is " + enteredName + "?\nEnter 'yes' to confirm or 'no' to type a new name.");
confirmation = sc.nextLine();
if (confirmation.equalsIgnoreCase("yes") || confirmation.equalsIgnoreCase("yes.")) {
System.out.println("Confirmed, " + enteredName + ".\n\nNow launching.");
}
} while (confirmation.equalsIgnoreCase("no") || confirmation.equalsIgnoreCase("no."));
}
}
示例运行:
What's your name again?Arvind
So, your name is Arvind?
Enter 'yes' to confirm or 'no' to type a new name.no
What's your name again?Kumar
So, your name is Kumar?
Enter 'yes' to confirm or 'no' to type a new name.no.
What's your name again?Avinash
So, your name is Avinash?
Enter 'yes' to confirm or 'no' to type a new name.yes
Confirmed, Avinash.
Now launching.
使用单个等号是一项赋值,如果要检查是否相等,请使用两个等号
// Sets value of confirmed to false then returns the new value
if (confirmed = false)
// Checks if confirmed is currently equal to false
if (confirmed == false)
// Checks if not confirmed (preferred syntax)
if (!confirmed)