该程序原本是一个调查工具。请帮助我有错误:
“线程中的异常”主“java.lang.Error:未解析的编译 问题:类型不匹配:无法从String转换为boolean at Conversation.main(Conversation.java:8)“
import java.util.Scanner;
public class Conversation {
public static void main(String[] args) {
String Ok;
int yes;
String age;
boolean okay = age;
Scanner in = new Scanner(System.in);
System.out.println("Please enter your name");
Ok = in.nextLine();
System.out.println("Hello, "+Ok);
System.out.println("Please enter your age, ");
yes = in.nextInt();
System.out.println("(Yes or No)Are you sure you are "+yes);
age = in.nextLine();
if (okay = "No"){
System.out.println("You are not allowed to lie \n in this program, please restart.");
}
}
}
尚未完成。 请帮助它是我的第一个自制程序。 我知道人们可以很容易地说出原则。
答案 0 :(得分:1)
正如错误消息所示,您无法将字符串分配给布尔变量:
String age;
boolean okay = age;
这是另一个问题:
if (okay = "No"){
System.out.println("You are not allowed to lie \n in this program, please restart.");
}
再次尝试将一个String分配给一个布尔变量,虽然它看起来像是要将一个String与一个布尔值进行比较(这也是非法的)。
您的变量名称令人困惑,但根据您的输出,我说您打算将对(Yes or No)Are you sure you are "+yes
问题的回答与"否"进行比较。 :
System.out.println("(Yes or No)Are you sure you are "+yes);
age = in.nextLine();
if (age.equals("No")){
System.out.println("You are not allowed to lie \n in this program, please restart.");
}
请注意,您应始终使用equals
而不是==
来比较字符串。如果这是您的代码中唯一的问题,我会将此问题视为重复。
答案 1 :(得分:1)
String age;
boolean okay = age;
您正在为boolean
分配String
个对象,这就是问题所在。
无法从String转换为boolean
另一个错误是:
if (okay = "No"){
,您无法执行此操作,okay
是boolean
变量,您将其与String
进行比较,这是不允许的。
正确的代码是if (okay = false)
。
PS:
"
对中包含的任何内容都是java中的String
。
示例:" Jon"是一个字符串。
答案 2 :(得分:0)
有两个编译错误:
首次编译错误:
boolean okay = age;
您不能将字符串值赋值给布尔变量,您必须指定true或false。
第二次编译错误:
if(okay =“No”)
在这里你必须检查布尔值,如:
if(okay == true)
或
if(okay == false)