【问题标题】:Java: wrong input from readLine() [duplicate]Java:来自 readLine() 的错误输入 [重复]
【发布时间】:2016-07-19 09:38:39
【问题描述】:

我正在从控制台读取输入,但每次我得到不同的字符串。例如。我正在输入“Bob”,然后检查它是否真的是“Bob”,但不是。另外,我检查了长度 - 它们是相同的。我做错了吗?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Please enter username: ");
        String username = null;
        try {
            username = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(username == "Bob")
            System.out.println("yes");
        else
            System.out.println("not");

        System.out.println(username.length());
        System.out.println("Bob".length());
    }
}

【问题讨论】:

  • 使用equals()比较字符串,而不是==

标签: java console readline


【解决方案1】:

使用equals 方法比较(非实习)字符串

public static void main(String[] args) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Please enter username: ");
    String username = null;
    try {
        username = reader.readLine();
        if ("Bob".equals(username))
            System.out.println("yes");
        else
            System.out.println("not");

        System.out.println(username.length());
        System.out.println("Bob".length());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

但自 java 1.5 起使用Scanner (https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html) 会更好/更容易

System.out.println("Please enter username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
if ("Bob".equals(username))
    System.out.println("yes");
else
    System.out.println("no");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多