2013-05-14 59 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