Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

having problems reading chars into array

Status
Not open for further replies.

Guy1978

MIS
Apr 21, 2005
7
BR
I have the following code that reads in an array of characters and then prints them out in alphabetical order (without sorting the array). The "tio.*" is a package that contains the readChar method. I've used it before without problems.
The problem with this code seems to be with the writing of characters to the array in the for statement. Whenever I try to debug the code by printing the contents of the array, all I get is the first three characters of the array. I'm not sure why.
I would appreciate any help. THANKS!

Code:
import tio.*;

class CharacterArray {
   public static void main(String[] args) {
      System.out.println("How many characters will you input? ");
      int charnumber = Console.in.readInt();
      char[] charray = new char[charnumber];
      System.out.println("Input the characters: ");
      for (int i = 0; i < charray.length; i++)
           charray[i] = (char)Console.in.readChar();
           printOrderedChars(charray);
   }

   static void printOrderedChars(char[] array) {
      char smallest;
      for (int i = 0; i < array.length - 1; i++) {
           smallest = array[i];
           for (int j = i + 1; j < array.length; j++)
                if (array[j] < smallest)
                    smallest = array[j];
           System.out.println(smallest);
      }	       
   }
}
 
Your indentation is misleading:
Code:
      for (int i = 0; i < charray.length; i++)
           charray[i] = (char)Console.in.readChar();
           printOrderedChars(charray);
should be
Code:
      for (int i = 0; i < charray.length; i++)
           charray[i] = (char)Console.in.readChar();
      printOrderedChars(charray);

I would test the code with a fixed char-Array, because your sorting isn't sorting very well:
Code:
 		String s = "How many characters will you input? ";
		int charnumber = s.length ();
		char [] charray = new char [charnumber];
		for (int i = 0; i < charray.length; i++)
			charray [i] = s.charAt (i);
		printOrderedChars (charray);

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top