2010-10-19 27 views
0

我試圖做一個基本的程序,允許用戶創建一個文本文件並添加一個單詞列表。當用戶寫入「停止」時 - 文件應該關閉。不幸的是,現在它只是一個無限循環。我在做什麼錯:Sentinel值關閉FileWriter(Java)

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


    public class WordList 
    { 
public static void main(String[] args) throws IOException 
{ 
    System.out.println("What would you like to call your file? (include extension)"); 

    Scanner kb = new Scanner(System.in); // Create Scanner 

    String fileName = kb.nextLine(); // assign fileName to name of file 

    PrintWriter outputFile = new PrintWriter(fileName); // Create the file 

    String input; 

    System.out.println("Please enter the next word or stopnow to end"); //Prompt user for a word 

    input = kb.nextLine(); // assign input as the word 

    while (input != "stopnow") 

    { 
    outputFile.println(input); // print input to the file 

    System.out.println("Please enter the next word or stopnow to end"); //Prompt user for a word 

    input = kb.nextLine(); // assign input as the word 

    } 

    outputFile.close(); //Close the File 

    System.out.println("done!"); 




} 

} 
+0

不是這樣。多少次必須*相同*這個問題應該回答? – 2010-10-20 00:06:17

回答

2

要檢查字符串是否相等,使用.equals

while (!input.equals("stopnow"))  
    { 
    outputFile.println(input); // print input to the file  
    System.out.println("Please enter the next word or stopnow to end"); //Prompt user for a word 
    input = kb.nextLine(); // assign input as the word  
    } 

什麼目前你正在做的是比較引用。

+0

如果現在沒有人回答這個問題,我現在每個人都應該出去吃午飯... – 2010-10-19 20:27:59

+0

所以,!=運算符只適用於int的嗎? – Woops4000 2010-10-19 20:28:50

+0

我正準備回答,但隨後一位同事停下來問我一個問題。愚蠢的工作妨礙了SO。 – jjnguy 2010-10-19 20:29:20