Jump to content

Recommended Posts

Hello, I am trying to comprehend how to compare the length between Strings.i have the following, to compare the length of 10 countries inserted by the user. It also orders them from lowest to highest:

public void load() {		teclado=new Scanner(System.in);		paises=new String[10];		for(int f=0;f<paises.length;f++) {			System.out.print("Ingrese el nombre del pais:");			paises[f]=teclado.next();		}	}	public void ordenar() {		for(int k=0;k<9;k++) {			for(int f=0;f<9-k;f++) {				if (paises[f].compareTo(paises[f+1])>0) {					String aux;					aux=paises[f];					paises[f]=paises[f+1];					paises[f+1]=aux;				}			}		}	} 

When I use the same method with numbers it works. For instance:

public void ordenar() {	   for(int k=0;k<9;k++){		for(int f=0;f<9-k;f++) {			if (vec[f+1]<vec[f]) {				int aux;				aux=vec[f];				vec[f]=vec[f+1];				vec[f+1]=aux;			  			}		}	  		}	}

So I deduce maybe :

if (paises[f].compareTo(paises[f+1])>0)

is not correct, because it's the only difference comparing it to the method on numbers.Is there any other way to compare the length between Strings? thank you in advance. p.s I took it from a tutorial which has been working fine till now. I have even checked the "compareTo" on other sites and it seems to be appropriate but I don't know why it's not working here. I would appreciate any help.

Edited by breastsroke
Link to post
Share on other sites

I don't know if it's necessary to say, but i am working on Java.I have realised the compareTo method works but only with Strings which start with the same letter. Then it arranges them properly.But it only arranges from lowest to higuest the String that start with the same letter.Isn't there a method which can be applied to any Strings regardless the letter they start with? p.s when above I say "order", I meant "arrange", "sort". English not being my native language..., sorry.xD

Link to post
Share on other sites
  • 5 weeks later...

hi,You must use length() on your string for it. compareTo is for sorting an array of object. Note that your sort is not usual, you should do that

ArrayList l = new ArrayList(); l.add( myCountry );Collections.sort( l );

Edited by japisoft
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...