Sentinel Wert zu schließen Filewriter (Java)
-
09-10-2019 - |
Frage
Ich versuche, ein Basisprogramm zu machen, die einen Benutzer ermöglicht, eine Textdatei zu erstellen und eine Liste von Worten, um es hinzuzufügen. Wenn der Benutzer schreibt „StopNow“ - sollte die Datei schließen. Leider ist es im Moment nur eine Endlosschleife. Was mache ich falsch:
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!");
}
}
Lösung
To check for String equality, use .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
}
What you are currently doing is comparing references.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow