【问题标题】:Beginner here - java IF ELSE used with text [duplicate]初学者在这里 - java IF ELSE 与文本一起使用[重复]
【发布时间】:2018-05-02 14:56:57
【问题描述】:

我刚开始阅读有关 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");

        }
    }}

【问题讨论】:

标签: java if-statement java.util.scanner


【解决方案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
}

更多关于ScannerGeeksForGeeks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多