java - 使用 boolean 值搜索重复项

标签 java boolean duplicates

当我需要打印出姓名列表时,我想使用 boolean 值来搜索重复项。所以我需要编写一个程序来读取文本文件中的名称并将其打印到控制台。但编译器在这种情况下不起作用。我不知道为什么?你们能帮我吗?

import java.io.*;
import java.util.*;

public class NameSorter 
{

  public static void main(String[] args) throws Exception
  {
    BufferedReader cin, fin;
    cin = new BufferedReader(new InputStreamReader(System.in));

     //Description
    System.out.println("Programmer: Minh Nguyen");
    System.out.println("Description: This program is to sort names stored in a file.");
    System.out.println();
    //Get input
    String fileName;
    System.out.print("Enter the file's name: ");
    fileName = cin.readLine();
    fin = new BufferedReader(new FileReader(fileName));
    int nNames = 0;
    String[] name = new String[8];

    //initialize array elements
    for(int i=0; i<name.length;i++)
    {
        name[i]=" ";
    }
    // read text file
    while(fin.ready())
    {
      String aName = fin.readLine();
      String temp =  aName;
      boolean check;
      if(temp.compareTo(" ")>0)
      {

          for(int i=0; i<name.length;i++)
          {
              if(temp.compareToIgnoreCase(name[i])==0)
              {
                  check = true;
                  break;
              }


          }

      }               
          if(nNames<name.length&& check = false)
          {
              name[nNames++] = temp;
          }

      }


    }
    fin.close();

    // Sort the names aphabetically.
    for(int i=0;i<nNames; i++)
    {
      int j;
      for(j=i+1;j<nNames; j++)
      {       
          if(name[i].compareToIgnoreCase(name[j])>0)
          {
          String temp = name[i];
          name[i] = name[j];
          name[j] = temp;            
          }  
      }
    }

    for(int i=0; i<name.length;i++)
        System.out.println(name[i]);

  }

}

最佳答案

您的代码是:

if(nNames<name.length && check = false)

check= false ,将 false 分配给 check。要将 checkfalse 进行比较,您可以使用 check==false!check

取决于您要验证的内容。下面的代码将消除编译错误:

check == false //checks if check is false

或者,

if(nNames<name.length && (check = false))
// above is same as if(nNames<name.length && false) // which will always be false

关于java - 使用 boolean 值搜索重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16547493/

相关文章:

java - 打开带参数的 PDF 文件

java - 如何在 Jenkins 多分支管道插件中从 pom 获取 artifactId 和版本

java - 如何让JPanel的长宽自动伸缩?

javascript - 如何将 localStorage 值设置为 false?

Javascript-使用 boolean 值设置超时

excel - 从 Excel 电子表格中删除包含重复数据的行?

javascript - 如何使用 Javascript 控制克隆的 <div> 的 css?

JAVA如何找到符号链接(symbolic link)指向的目标文件路径?

java - 使用 MySQL 在 Hibernate 中未正确映射 boolean 值

java - 为什么java有很多重复的方法?