Hello and Happy Thanksgiving (to those who celebrate it),
I have a small program that needs to read data off of a text file (name, city and age) and store it in an array. The program asks the user for a city name, and it's supposed to loop through the array and print out the names of people from that city. Now, my problem starts when I ask for the town to look for, since there are two-word towns (e.g. San Juan). I was using input.next() but it was only accepting the first word. I changed it to input.nextLine() and now it skips that part; it just exits the program.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class projectCOMP2315
{
public static void main( String [] args )
{
Scanner input = new Scanner (System.in);
// Declaracion de variables
String nombreDocTXT = null,
arregloTotalDatos [] = new String [600],
stringPueblo = null,
trimmedElement = null;
int totalDatos = 0,
opcion = 0,
x = 0,
nuevoIndice = 0;
boolean flag = false;
try
{
System.out.print( "¿Cual es el nombre del archivo a leer? " );
nombreDocTXT = input.next();
FileReader reader = new FileReader( nombreDocTXT );
BufferedReader in = new BufferedReader( reader );
String leeUnoAUno = in.readLine();
while( leeUnoAUno != null )
{
arregloTotalDatos[ totalDatos ] = leeUnoAUno;
leeUnoAUno = in.readLine();
totalDatos = totalDatos + 1;
}
System.out.print(" \n");
for ( x = 1 ; x <= 45 ; x++ )
{
System.out.print( "*" );
}
System.out.print(" M E N U ");
for ( x = 1 ; x <= 45 ; x++ )
{
System.out.print( "*" );
}
System.out.print(" \n1. Print the names of people from a particular town. ");
System.out.print(" \n2. Imprimir el nombre de todas …. ");
System.out.print(" \n3. Imprimir los nombres de todas …. ");
System.out.print(" \n4. Imprimir la lista completa de ….. ");
System.out.print(" \n5. Indicar cuántas personas hay en un …… ");
System.out.print(" \n");
for ( x = 1 ; x <= 101 ; x++ )
{
System.out.print( "*" );
}
System.out.print(" \n9. Salir del programa ");
System.out.print(" \n");
for ( x = 1 ; x <= 101 ; x++ )
{
System.out.print( "*" );
}
System.out.print(" \nSeleccion: ");
opcion = input.nextInt();
in.close( );
}
catch( FileNotFoundException filenotfoundexxption )
{
System.out.println( nombreDocTXT + " no existe." );
}
catch( IOException ioexception )
{
ioexception.printStackTrace( );
}
switch (opcion)
{
case 1:
{
System.out.println( "\n¿De que pueblo desea buscar informacion? " );
String pueblo = input.nextLine();
stringPueblo = pueblo.trim();
for ( x = 0 ; x < arregloTotalDatos.length ; x++ )
{
trimmedElement = arregloTotalDatos[ x ].trim();
if ( (stringPueblo) .equals (trimmedElement) )
{
nuevoIndice = x - 1;
System.out.println(arregloTotalDatos[ nuevoIndice ]);
flag = true;
}
}
if ( flag == false )
{
System.out.println( pueblo + "\nNo hay un record con ese pueblo." );
}
}
case 9:
{
break;
}
} // termina switch
} // termina main
} // termina projectCOMP2315