java丢弃最后一个ArrayList
我有这个程序,它应该存储在一个txt文件的信息所要求的键盘,但这并没有保存最后的要求将是一个ArrayList称为“科尔”,如果我可以帮助这个请
package lab1;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Lab1 {
public static void main(String[] args) {
// TODO code application logic here
int opc;
Scanner entrada = new Scanner(System.in);
System.out.println("MENU: Eligue su opcion\n");
System.out.println("1.- Crear archivo");
System.out.println("2.- Mas opciones para mostrar");
System.out.println("3.- Escritura en el archivo");
System.out.println("4.- Salir\n");
System.out.println("Introdusca su opcion:");
opc = entrada.nextInt();
if (opc == 1){
FileWriter fichero = null;
PrintWriter pw = null;
try{
//Tiempo al programa de suspencion.
Thread.sleep(2000);
//se abre el archivo txt si este esta creado y el TRUE hace que no borre la informacio que este contiene si es que existe el txt.
fichero = new FileWriter("C:\\Users\\Levenor\\Desktop\\Test\\test.txt", true);
pw = new PrintWriter(fichero);
//En estos parametros se pide la informacion para agregarlo en una lista para luego colocar en el txt.
ArrayList<String> nombre = new ArrayList<String>();
System.out.println("Ingrese Nombre: ");
nombre.add(entrada.nextLine());
Thread.sleep(8000);
ArrayList<String> rut = new ArrayList<String>();
System.out.println("Ingrese RUT: ");
rut.add(entrada.nextLine());
Thread.sleep(8000);
ArrayList<String> edad = new ArrayList<String>();
System.out.println("Ingrese EDAD: ");
edad.add(entrada.nextLine());
Thread.sleep(4000);
// here is arraylist is not save in the archive txt
ArrayList<String> cole = new ArrayList<String>();
System.out.println("Ingrese COLEGIO: ");
cole.add(entrada.nextLine());
Thread.sleep(4000);
//Esta linea hace que las listas se guarden en el archivo de txt.
pw.println("" +nombre +rut +edad +cole);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Nuevamente aprovechamos el finally para
// asegurarnos que se cierra el fichero.
if (null != fichero)
fichero.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
# 1 楼答案
你在} 的调用-它没有正确地推进输入。调用^{} 时,它使用
opc = entrada.nextInt();
之后缺少对^{int
值,但不使用末尾的换行符。因此,您需要调用nextLine()
以将Scanner
移过它系统也应该暂停——你不需要使用
Thread.sleep()
——这是它与你的输入不正确对齐的症状。您还应该确保关闭finally
块中的Scanner entrada
示例代码:
示例输出: