【问题标题】:Java input error. I can't validate the string entered [duplicate]Java 输入错误。我无法验证输入的字符串 [重复]
【发布时间】:2012-05-23 17:48:28
【问题描述】:

可能重复:
Java string comparison?

晚上好。下面的代码没有给出错误,但是当我尝试验证输入的字符串时,它总是假设我没有输入“YES”,即使我确实使用了 toUpperCase() 方法。这一定是一个非常基本的错误,但我现在无法弄清楚,因为我只是在学习这种语言的基础知识。代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main{

    public static void main(String[] args) throws IOException{

        byte counter = 1;
        boolean myCondition = false;
        String answer;
        List<String> myList = new ArrayList<String>();
        BufferedReader objReader = new BufferedReader(new InputStreamReader(System.in));

        do{
            System.out.println("Enter the #" +counter +" person's name:");
            myList.add(objReader.readLine());
            counter++;
            System.out.println("Would you like to add another name to the list? yes/no");
            answer = objReader.readLine();
            if (answer.toUpperCase() == "YES"){
                myCondition = true;
            }

        } while (myCondition);

        System.out.println("The list of names you entered, looks like this:\n");
        for (String name: myList)
            System.out.println(name);

        System.out.println("\nPress <Enter> to randomize the list of names you entered.");
        objReader.readLine();
        Collections.shuffle(myList);

        System.out.println("Done! \nPress <Enter> to see how the randomized list looks like.\n");
        objReader.readLine();
        for(String nombre: myList)
            System.out.println(nombre);

    }

}

在此先感谢您提供任何帮助和/或提示。

【问题讨论】:

    标签: java input io console


    【解决方案1】:

    比较字符串时应该使用 .equals() 方法而不是 ==:

    answer.toUpperCase().equals("YES")
    

    这是大多数人在开始 java 编程时会犯的错误,您会感到安慰 :)

    【讨论】:

    • 非常感谢!我已经感到沮丧了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多