Sentinel Valor para cerrar FileWriter (Java)
-
09-10-2019 - |
Pregunta
Estoy intentando hacer un programa básico que permite a un usuario crear un archivo de texto y añadir una lista de palabras a la misma. Cuando el usuario escribe "StopNow" - el archivo se debe cerrar. Desafortunadamente, en este momento es sólo un bucle infinito. ¿Qué estoy haciendo mal:
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!");
}
}
Solución
Para comprobar la igualdad de cuerdas, uso .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
}
Lo que está haciendo actualmente está comparando referencias.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow