2010-10-19 2 views
0

Я пытаюсь создать базовую программу, которая позволяет пользователю создавать текстовый файл и добавлять к нему список слов. Когда пользователь пишет «stopnow» - файл должен закрываться. К сожалению, сейчас это просто бесконечный цикл. Что я делаю неправильно:Значение 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

Не снова. Сколько раз нужно * одинаково * на этот вопрос ответить? –

ответ

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

Каждый должен быть на обед, если на это никто не ответил, но я уже сейчас ... –

+0

так, оператор! = Только для int's? – Woops4000

+0

Я собирался ответить на него, но затем сотрудник остановился, чтобы задать мне вопрос. Глупые работы мешают SO. – jjnguy