我刚开始阅读有关JAVA的内容,我想制作一个小程序,当我使用Scanner时,我输入“是”,“否”或只是随机的东西,我会得到不同的消息。如果有线条的问题:
if (LEAVE == "yes") {
System.out.println("ok, lets go");
if (LEAVE == "no") {
System.out.println("you dont have a choice");
} else {
System.out.println("it's a yes or no question");
我收到错误:运算符“==”无法应用于“java.util.scanner”,“java.lang.String”。我在一个网站上看到,如果我用.equals替换“==”会更好,但我仍然会收到错误..
请帮助:S
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner LEAVE = new Scanner(System.in);
System.out.println("do you want to answer this test?");
LEAVE.next();
System.out.println("first q: would you leave the hotel?");
LEAVE.next();
if (LEAVE == "yes") {
System.out.println("ok, lets go");
}
LEAVE.nextLine();
if (LEAVE == "no") {
System.out.println("you dont have a choice");
LEAVE.nextLine();
} else {
System.out.println("it's a yes or no question");
}
}}
答案 0 :(得分:1)
Scanner LEAVE = new Scanner(System.in);
意味着LEAVE是Scanner类对象。右。
if (LEAVE == "yes")
您正在将Scanner类型对象与String类型对象进行比较,因此您将获得
Operator "==" cannot be applied to "java.util.scanner", "java.lang.String"
现在考虑
LEAVE.next();
你正在调用属于LEAVE对象的next()。下一个函数假设读取一个值并将其返回给您。所以你所做的就是在另一个String
类型的对象中接收这个值,然后进一步将它与'YES'或'NO'或其他任何东西进行比较。
String response = LEAVE.next()
if(response.equalsIgnoreCase("yes")){
// do something
}else if(response.equalsIgnoreCase("no")){
// do something else
}
有关Scanner
课程的更多信息
GeeksForGeeks