【问题标题】:Simple String comparison is not working简单的字符串比较不起作用
【发布时间】:2012-12-10 03:43:33
【问题描述】:

我需要创建一个循环链接列表,其中节点具有 Rider 类对象,每个 Rider 都有一个名称和一个布尔值。给定文本输入,程序会扫描输入并将骑手添加到“行”

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

    Scanner read = new Scanner(System.in);
    CLLOfRiders line= new CLLOfRiders();
    System.out.print("Welcome to Project 1." +
            "\nWhat is the name of the data file?\n>");
    String input=read.nextLine();
    File f= new File(input);
    Scanner fileread = new Scanner(f).useDelimiter(" - |\n");
    while(fileread.hasNext())
    {
        Rider r=new Rider();
        r.name=fileread.next();
        System.out.println(r.name);
>>>>>       if(fileread.next().equals("Y")) <<<<<   
        r.changePass(true);
        line.addRider(r);
        System.out.println(r.speedPassStatus);
    }
    System.out.println("Finished reading the file.");
    line.showWait();

我的问题是箭头突出显示的 if 语句没有运行,所以我无法将 Riders 布尔值设置为正确的值。根据我的说法,这似乎是应该顺利运行的简单代码?请帮忙。抱歉,这是我的第一篇文章。

【问题讨论】:

  • 对 fileread.next() 执行 trim() 并查看 if 的开始和结束大括号在哪里?
  • 只有一行 if 语句
  • 好的。然后我会确保空格或区分大小写或两者都不会导致问题。
  • 我在扫描仪上设置了分隔符以删除所有空格,因此字符串传递应该只有一个字符长。我尝试使用 equalsIgnoreCase 并没有做任何事情
  • 我认为您应该尝试打印在 if 语句中读取的值并添加引号将有助于确保读取值中有任何空格

标签: java string linked-list equals


【解决方案1】:
...   
r.name=fileread.next();
System.out.println(r.name);
if(fileread.next().equals("Y"))
...

您在循环中使用了两次fileread.next()

把第二个改成

if(r.name.equals("Y"))

【讨论】:

  • 抱歉混淆,两次读取是 Rider 类的不同参数,名称是一部分,第二次读取读取单个字符串,我查看该字符串以查看布尔值是否为真或错误的。我试过制作一个字符串传递对象,但它也没有比较
  • 如果您打印String s = fileread.next(); System.out.println("'"+s+"'");,您会得到什么? (注意我添加了单引号)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 2014-04-03
  • 2012-01-22
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多