My program (with bubble) is supposed to ask the user if he wants to enter another license plate and name. They should not be more than 5, however if I enter less than 5 data at the time of printing, the message appears NULL
in the spaces where no data was entered. How can I fix that problem?
Here my code:
import java.util.*;
public class bubble{
public static void main(String[]args){
Scanner entrada;
entrada=new Scanner(System.in);
Scanner sc=new Scanner(System.in);
Scanner entrada2;
entrada2=new Scanner(System.in);
String[] nombre=new String[6];
String auxnombre;
int x=0;
int y=0;
int[] matricula= new int[6];
int b=0;
int a=0;
int another=0;
int opcion=0;
int auxmatricula;
do{
a++;
System.out.println("No. de Registro " +a);
System.out.println("Ingresa tu numero contable");
matricula[a]=entrada.nextInt();
System.out.println("Ingresa tu nombre:");
nombre[a]=sc.nextLine().toUpperCase();
System.out.println("Deseas otro proceso? 1.si 2.no");
another=entrada.nextInt();
if (a>=5)
{
another=2;
}
}while(another==1);
for(int i=1; i<5; i++)
{
for(y=1; y<5; y++)
{
if(matricula[y]>matricula[y+1])
{
auxmatricula=matricula[y];
matricula[y]=matricula[y+1];
matricula[y+1]=auxmatricula;
auxnombre=nombre[y];
nombre[y]=nombre[y+1];
nombre[y+1]=auxnombre;
}
}
}
for(int i=1; i<=5; i++)
{
System.out.println("Numero Contable: "+matricula[i]+ "\n Nombre: "+nombre[i]);
}
}
}
Try the following code:
Simplify your code a bit by using lists and without a defined size, so only the elements entered by keyboard will be stored.