Bienvenido: ( Identificarse | Registrarse )      
Foros de Trucos Windows
 
Closed TopicStart new topicStart Poll

Outline · [ Estándar ] · Lineal+

> Problema en Java

Marzzipan
post Mar 12 2008, 03:34 AM
Publicado: #1


Miembro
**

Grupo: Members
Mensajes: 38
Registrado: 21-July 06
Miembro nº: 174.802



Buenas noches a todo el foro, bueno espero no revolverles, al parecer me eh trabado en una parte de mi programa, ya que quiero que haga lo siguiente:

Que me pida ciertos datos y al final me indique que numero del libro deseo prestar(es un supuesto programa para una biblioteca) si por ejemplo pongo 1 me imprima en la pantalla:

"El estudiante xy de matricula ab ah prestado el libro "aca va el nombre del libro".

Debe existir un archivo txt con los nombres de ciertos libros ya escritos de esta manera

Fisica Moderna <Esta seria la linea 1>

Geometria analitica <Esta la 3>

Robin Hood <Esta la 5>

Atlas Mundial <Esta la 7>

El Mundo Del Mañana <Esta la 9>

y así sucesivamente; esto es lo que tengo hasta ahora


CODE
//Aca es el codigo para leer una linea especifica del archivo//
import java.io.*;
import javagently.*;
class ProgramaBiblioteca {
public static void showLines(String fileName, int startLine, int endLine)  {
       String line = null;
       int currentLineNo = 0;
       BufferedReader in = null;
       try {
           in = new BufferedReader (new FileReader("ListadeLibros.txt"));
           while(currentLineNo<startLine) {
               if (in.readLine()==null) {
                   throw new IOException("Archivo demasiado pequeño");
               }
               currentLineNo++;
           }
           while(currentLineNo<=endLine) {
               line = in.readLine();
               if (line==null) {
                   return;
               }
               System.out.println(line);
               currentLineNo++;
           }
           
       } catch (IOException ex) {
           System.out.println("Hubo un Problema al leer el archivo.\n" + ex.getMessage());
       } finally {
           try { if (in!=null) in.close(); } catch(IOException ignore) {}
       }
   }

//Aca termina el codigo y empieza el programa//

//Aca comienza el codigo que va a leer todo lo que ingrese en el teclado y lo va a imprmir//

public static void main (String [] args) throws IOException {
 InputStreamReader entrada=new InputStreamReader(System.in);
    BufferedReader teclado=new BufferedReader(entrada);
 BufferedReader in=Text.open(System.in);
 System.out.println("Bienvenido al Programa Bibliotecario (Codigo fuente hecho por Blackmore)");
 System.out.println();
 Text.prompt("Escriba solo el primer nombre del estudiante: ");
 String nombre=Text.readString(in);
 System.out.println();
 Text.prompt("Escriba su primer apellido: ");
 String apellido=Text.readString(in);
 System.out.println();
 Text.prompt("Escriba su segundo apellido: ");
 String apellido2=Text.readString(in);
 System.out.println();
 Text.prompt("Escriba su matricula: ");
 String matricula=Text.readString(in);
 System.out.println();
 Text.prompt("Ingrese con numeros la fecha de hoy: ");
 String fechaprestamo=Text.readString(in);
 System.out.println();
 Text.prompt("Escriba el numero del libro prestado: ");
 int numerolibro=Text.readInt(in);
 System.out.println();
    {
     if(numerolibro == 1)
     showLines("Profiles.ini", 0,3);
    }
    {
     if(numerolibro == 2)
     showLines("Profiles.ini", 4,6);
    }
 System.out.println();
 System.out.println("El/La estudiante " + nombre + " " + apellido + " " + apellido2 + " con matricula " + matricula + " ha prestado el libro " + numerolibro + " a la fecha del " + fechaprestamo);
}
}

//Fin del programa//


Donde el codigo // showLines("Profiles.ini", 0,3); // lee la linea del cero a la 2 ( no se porque pero si pongo showLines("Profiles.ini", 1,3); no me lee la primera linea.

El problema radica en que cuando me pregunta

Text.prompt("Escriba el numero del libro prestado: ");
int numerolibro=Text.readInt(in);

A la hora de imprimir todo como debe

"El estudiante xy de matricula ab ah prestado el libro "aca va el nombre del libro".

Solo imprime: "El estudiante xy de matricula ab ah prestado el libro 1( o 2 o segun el numero que haya puesto)" Al parecer mi sentencia if no funciona, y eso es por los bajos conocimientos que tengo sobre el codigo para que lea una linea en especifico, aca les dejo el original de este:

CODE
import java.io.*;
public class TestRead2 {
   public static void showLines(String fileName, int startLine, int endLine)  {
       String line = null;
       int currentLineNo = 0;

       BufferedReader in = null;
       try {
           in = new BufferedReader (new FileReader("Aca va el nombre del archivo"));
           
           //read to startLine
           while(currentLineNo<startLine) {
               if (in.readLine()==null) {
                   // oops, early end of file
                   throw new IOException("File todo small");
               }
               currentLineNo++;
           }
           
           //read until endLine
           while(currentLineNo<=endLine) {
               line = in.readLine();
               if (line==null) {
                   // here, we'll forgive a short file
                   // note finally still cleans up
                   return;
               }
               System.out.println(line);
               currentLineNo++;
           }
           
       } catch (IOException ex) {
           System.out.println("Problem reading file.\n" + ex.getMessage());
       } finally {
           try { if (in!=null) in.close(); } catch(IOException ignore) {}
       }
   }

   
   public static void main(String[] args) {
       showLines("Profiles.ini", 0,1);
   }
}


Siento hacerlo tan largo y espero que me entiendan, gracias de antemano.


User is offlineProfile CardPM
Go to the top of the page
+Quote Post
rob1104
post Mar 12 2008, 09:01 AM
Publicado: #2


Xbox Live... The best thing ever happened around videogames
Group Icon

Grupo: Moderadores
Mensajes: 1.623
Registrado: 7-March 05
Desde: Matamoros, Tamaulipas, Mexico
Miembro nº: 93.342



Hola, a ver si entendi, el unico problema es que te muestra el numero del libro en vez del nombre??
Eso es obvio, dado que estas mostrando la variable numeroLibro unsure.gif , lo que puedes hacer es guardar en un string el contenido de ShowLines, pero tendrias que modificar el metodo ShowLines para que te devuelva el string en vez de mostrarlo en pantalla, si es eso te ayudo a hacerlo, es facil, si no es que no entendi bien y agradeceria que lo explicaras de nuevo.

Saludos

PD: Por cierto no pude probar tu codigo, ya que no tengo el paquete: javagently.* y nunca habia oido hablar de él, ya que tengo mucho tiempo de no usar java porque me enamoré de .NET new18.gif


User is offlineProfile CardPM
Go to the top of the page
+Quote Post
Marzzipan
post Mar 13 2008, 05:27 AM
Publicado: #3


Miembro
**

Grupo: Members
Mensajes: 38
Registrado: 21-July 06
Miembro nº: 174.802



Si eso es exacatamente lo que me pasa, me muestra el numero que puse cuando me lo pidio y no el nombre del libro que esta en el archivo de texto para que lo lea y lo imprima el ShowLines. Por ejemplo si pongo 1 que me muesta las primeras dos lineas del archivo, si pongo 2 que me muesta la linea 3 y 4 y asi sucesivamente. Perdon por el package de javagently aca te paso el codigo solo tienes que correrlo y te crea la clase, bueno tu sabes como biggrin20jy.gif , muchas gracias por responder.

CODE
package javagently;

import java.io.*;
import java.util.*;
import java.text.*;

public class Text {

 public Text () {};

 /* The All New Famous Text class     by J M Bishop  Aug 1996
  *            revised for Java 1.1 by Alwyn Moolman Aug 1997
  *            revised for efficiency by J M Bishop Dec 1997
  *            revised with renamed output methods
  *              by J M Bishop in July 1999
  *
  * Provides simple input from the keyboard and files.
  * Now also has simple output formatting methods
  * and file opening facilities.
  *
  * public static void   prompt (String s)
  * public static int    readInt (BufferedReader in)
  * public static double readDouble (BufferedReader in)  
  * public static String readString (BufferedReader in)  
  * public static char   readChar (BufferedReader in)
  * public static String writeInt (int number, int align)
  * public static String writeDouble
                  (double number, int align, int frac)
  * public static BufferedReader open (InputStream in)
  * public static BufferedReader open (String filename)
  * public static PrintWriter create (String filename)
  */

 private static StringTokenizer T;
 private static String S;

 public static BufferedReader open (InputStream in)  {
   return new BufferedReader(new InputStreamReader(in));
 }

 public static BufferedReader open (String filename)
throws FileNotFoundException {
   return new BufferedReader (new FileReader (filename));
 }
 
 public static PrintWriter create
 (String filename) throws IOException {
   return new PrintWriter (new FileWriter (filename));
 }

 public static void prompt (String s) {
   System.out.print(s + " ");
   System.out.flush();
 }

 public static int readInt (BufferedReader in) throws IOException {
     if (T==null) refresh(in);
     while (true) {
       try {
         return Integer.parseInt(T.nextToken());
       }
       catch (NoSuchElementException e1) {
         refresh (in);
       }
       catch (NumberFormatException e2) {
         System.out.println("Error in number, try again.");
       }
     }
  }

public static char readChar (BufferedReader in) throws IOException {
     if (T==null) refresh(in);
     while (true) {
       try {
         return T.nextToken().trim().charAt(0);
       }
       catch (NoSuchElementException e1) {
         refresh (in);
       }
     }
  }

public static double readDouble (BufferedReader in) throws IOException {
     if (T==null) refresh(in);
     while (true) {
       try {
         String item = T.nextToken();
         return Double.valueOf(item.trim()).doubleValue();
       }
       catch (NoSuchElementException e1) {
         refresh (in);
       }
       catch (NumberFormatException e2) {
         System.out.println("Error in number, try again.");
       }
     }
  }

 public static String readString (BufferedReader in) throws IOException {
   if (T==null) refresh (in);
   while (true) {
     try {
       return T.nextToken();
     }
     catch (NoSuchElementException e1) {
       refresh (in);
     }
   }
 }

 private static void refresh (BufferedReader in) throws IOException {
   S = in.readLine ();
   if (S==null) throw new EOFException();
   T = new StringTokenizer (S);
 }

 //  Format methods
 //  --------------

 private static DecimalFormat N = new DecimalFormat();
 private static final String spaces = "                    ";
 
 public static String format(double number, int align, int frac) {
   N.setGroupingUsed(false);
N.setMaximumFractionDigits(frac);
N.setMinimumFractionDigits(frac);
String num = N.format(number);
if (num.length() < align)
   num = spaces.substring(0,align-num.length()) + num;
   return num;
 }
 
 public static String format(int number, int align) {
   N.setGroupingUsed(false);
   N.setMaximumFractionDigits(0);
   String num = N.format(number);
   if (num.length() < align)
      num = spaces.substring(0,align-num.length()) + num;
   return num;
 }

 public static String writeDouble (double number, int align, int frac) {
   // Deprecated in July 1999 but retained for compatability
return format (number, align, frac);
 }
 
 public static String writeInt (int number, int align) {
   // Deprecated in July 1999 but retained for compatability
  return format (number, align);
 }
}



User is offlineProfile CardPM
Go to the top of the page
+Quote Post
rob1104
post Mar 13 2008, 09:25 PM
Publicado: #4


Xbox Live... The best thing ever happened around videogames
Group Icon

Grupo: Moderadores
Mensajes: 1.623
Registrado: 7-March 05
Desde: Matamoros, Tamaulipas, Mexico
Miembro nº: 93.342



Hola, pues bueno, haciendo lo que te dije en el post anterior:
QUOTE
lo que puedes hacer es guardar en un string el contenido de ShowLines, pero tendrias que modificar el metodo ShowLines para que te devuelva el string en vez de mostrarlo en pantalla
.

Primero que nada cambiamos el tipo de la funcion ShowLines de void a String:
CODE
public static String showLines(String fileName, int startLine, int endLine)


Ahora en el bucle:
CODE
while(currentLineNo<=endLine) {
              line = in.readLine();
              if (line==null) {
                  return;
              }
Cambialo a
CODE
while(currentLineNo<=endLine) {
              line = in.readLine();
              if (line==null) {
                  return "";
              }
es decir, poner las comillas al return (recuerda que tenemos que devolver una string, asi que al final del mismo, si todo salio bien y no hay excepciones retornamos el string line, para ello eliminamos la linea:
CODE
//System.out.println(line);
(la comenté) y al final del metodo ShowLines pones:
CODE
return line
.

Ya tenemos el metodo ShowLines devolviendonos el nombre del libro en vez de mostrarlo en pantalla, faltan 2 cosas: declarar un string para guardar el nombre del libro y corregir la sentencia if (yo en tu lugar usaria un switch) , de tal modo que quede mas o menos:
CODE
String nombreLibro = new String();
switch(numerolibro)
{
 case 1:
  nombreLibro=showLines("profiles.ini",0,0);
  break;
 case 2:
   nombreLibro=showLines("profiles.ini",2,2);
   break;
 case 3:
  nombreLibro=showLines("profiles.ini",4,4);
  break;
 case 4:
  nombreLibro=showLines("profiles.ini",6,6);
               break;
 case 5:
  nombreLibro=showLines("profiles.ini",8,8);
               break;
default:
 System.out.println("Numero de libro no existe");
}

Y por ultimo modificar el println para que muestre el nombre y no el numero:
CODE
System.out.println("El/La estudiante " + nombre + " " + apellido + " " + apellido2 + " con matricula " + matricula + " ha prestado el libro " + nombreLibro + " a la fecha del " + fechaprestamo);


Te dejó el codigo completo por si se me pasó algo:
CODE
//Aca es el codigo para leer una linea especifica del archivo//
import java.io.*;
import javagently.*;

class ProgramaBiblioteca {
public static String showLines(String fileName, int startLine, int endLine)  {
      String line = null;
      int currentLineNo = 0;
      BufferedReader in = null;
      try {
          in = new BufferedReader (new FileReader("ListadeLibros.txt"));
          while(currentLineNo<startLine) {
              if (in.readLine()==null) {
                  throw new IOException("Archivo demasiado pequeño");
              }
              currentLineNo++;
          }
          while(currentLineNo<=endLine) {
              line = in.readLine();
              if (line==null) {
                  return "";
              }
              //System.out.println(line);
              currentLineNo++;
          }
         
      } catch (IOException ex) {
          System.out.println("Hubo un Problema al leer el archivo.\n" + ex.getMessage());
      } finally {
          try { if (in!=null) in.close(); } catch(IOException ignore) {}
      }
      return line;
  }

//Aca termina el codigo y empieza el programa//

//Aca comienza el codigo que va a leer todo lo que ingrese en el teclado y lo va a imprmir//

public static void main (String [] args) throws IOException {
InputStreamReader entrada=new InputStreamReader(System.in);
   BufferedReader teclado=new BufferedReader(entrada);
BufferedReader in=Text.open(System.in);
System.out.println("Bienvenido al Programa Bibliotecario (Codigo fuente hecho por Blackmore)");
System.out.println();
Text.prompt("Escriba solo el primer nombre del estudiante: ");
String nombre=Text.readString(in);
System.out.println();
Text.prompt("Escriba su primer apellido: ");
String apellido=Text.readString(in);
System.out.println();
Text.prompt("Escriba su segundo apellido: ");
String apellido2=Text.readString(in);
System.out.println();
Text.prompt("Escriba su matricula: ");
String matricula=Text.readString(in);
System.out.println();
Text.prompt("Ingrese con numeros la fecha de hoy: ");
String fechaprestamo=Text.readString(in);
System.out.println();
Text.prompt("Escriba el numero del libro prestado: ");
int numerolibro=Text.readInt(in);


System.out.println();

String nombreLibro = new String();
switch(numerolibro)
{
 case 1:
  nombreLibro=showLines("profiles.ini",0,0);
  break;
 case 2:
   nombreLibro=showLines("profiles.ini",2,2);
   break;
 case 3:
  nombreLibro=showLines("profiles.ini",4,4);
  break;
 case 4:
  nombreLibro=showLines("profiles.ini",6,6);
               break;
 case 5:
  nombreLibro=showLines("profiles.ini",8,8);
               break;
default:
 System.out.println("Numero de libro no existe");
}



System.out.println();
System.out.println("El/La estudiante " + nombre + " " + apellido + " " + apellido2 + " con matricula " + matricula + " ha prestado el libro " + nombreLibro + " a la fecha del " + fechaprestamo);
}
}

//Fin del programa//

Por cierto, talvez te preguntes porque al metodo showLines le puse como parametros 0,0 2,2 4,4.. etc, pues bueno analizandolo bien si notas que es:
showLines(String FileName, int StartLine, int EndLine)

Osea que le estas pasando por parametro la primera linea a leer y la ultima, pero como solo nos interesa una, entonces la primera linea y la ultima seran siempre la misma :D, claro estoy tomando en cuenta que hay una linea en blanco entre libro y libro, por eso voy de 2 en 2.

Espero te sirva.

Saludos
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
Marzzipan
post Mar 14 2008, 02:56 AM
Publicado: #5


Miembro
**

Grupo: Members
Mensajes: 38
Registrado: 21-July 06
Miembro nº: 174.802



clap.gif Muchisimas gracias rob1104 me ha sido de demasiada ayuda tu explicación y el código, y gracias tambien por responder smile.gif . El que sabe, sabe.
User is offlineProfile CardPM
Go to the top of the page
+Quote Post
rob1104
post Mar 14 2008, 04:01 PM
Publicado: #6


Xbox Live... The best thing ever happened around videogames
Group Icon

Grupo: Moderadores
Mensajes: 1.623
Registrado: 7-March 05
Desde: Matamoros, Tamaulipas, Mexico
Miembro nº: 93.342



De nada, un placer coolio0ju.gif
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

 
Closed TopicTopic OptionsStart new topic

Collapse

> Topicos similares

Problema con Internet en Red Sakura_87 35 2 Hoy, 01:24 AM
By: Sakura_87
Problema de navegacion drlemon52 2 0 Hoy, 12:07 AM
By: drlemon52
problema de virus dejo el log patxirules 59 7 Ayer, 11:07 PM
By: Caito
Problema con el inicio de windows tavo.cmd 116 2 Ayer, 10:23 PM
By: tavo.cmd
Problema con la activación de windows pane13 27 0 Ayer, 10:00 PM
By: pane13

Google
Web www.trucoswindows.net