初学者在这里 - java IF ELSE 与文本一起使用



我刚刚开始阅读有关JAVA的内容,我想制作一个小程序,当使用扫描仪时,我键入"是","否"或只是随机的东西,我会得到不同的消息。如果与行的问题:

 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");
        }
    }}
Scanner LEAVE = new Scanner(System.in);

暗示 LEAVE 是扫描程序类对象。右。

if (LEAVE == "yes")

正在将扫描仪类型对象与字符串类型对象进行比较,因此您得到

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类的更多信息极客ForGeeks

最新更新