2013-05-14 61 views
0

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

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]); 

    } 

} 
+1

这将有助于如果你包括你看到的错误消息。 “它不起作用”只是以你不喜欢的方式标记你。另外,尝试将'check = false'更改为'check == false'。 – 2013-05-14 15:46:21

回答

1

你的代码是:

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

check= false,分配给falsecheck。要比较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 
+0

谢谢,它现在可以编译,但我仍然没有得到想要的结果。我需要在文本文件中读取名称。我的算法是首先跳过文件中的空白行,然后跳过重复项,最后将适当的值分配给基于数组的列表并将其打印出来。我知道我的程序不工作,但我不知道为什么:(你可以给我一些线索,我不得不使用基于数组的列表,因为这是我的作业的要求 – 2013-05-14 15:58:00

+0

有人可以帮助,所以绝望! – 2013-05-14 17:33:24

+0

我抓住你的代码,根据这个答案修复它,然后还找到了一个额外的花括号,我将它编译并运行在一个带有名称列表的文本文件中,它可以工作 – 2013-05-14 19:05:21