Solved

Storing a string of ints and spaces into an array

Posted on 2004-08-29
86
1,706 Views
Last Modified: 2009-12-16
Hello,

Wow!  I'm back after a long summer.  Hope you had a nice one too.  Anyways, I'm trying to refresh my memory on java.  I was trying to store a string of ints and spaces into an array.  After I read the data from "input.txt", I want it to print an exact copy to an "output.txt".  The problem is, when I store it into an array, I want to store each INDIVIDUAL int - not the whole string.

Example input:

0 _ _ 2 _ _ _ 4 _ 3 _ 1     // input string in "input.txt"; "_" represent spaces

Store to an array:

|0|_|_|2|_|_|_|4|_|3|_|1|      // each integer has it's own position in array
 0  1 2  3 4  5  6 7  8 9 10 11     // array length depends on the length of the string (or maybe there's a better way to do this?)

Output:

0 _ _ 2 _ _ _ 4 _ 3 _ 1


After I get this done, I want to implement the QuickSort function to sort the numbers.  If I have questions on that, I'll make another Question in the Java section.  Thank you in advance!!

-luna621 =^^=

0
Comment
Question by:luna621
  • 34
  • 23
  • 19
  • +4
86 Comments
 

Author Comment

by:luna621
ID: 11928570
Here's my incomplete code:

 import java.io.*;

 public class ReadInputArray {

 int iLength = 0;
 static PrintStream ps;

    public static void readData() throws Exception {

        // Read input array

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
        String input = "";

        File output = new File("output.txt"); // writes to output.txt
        FileOutputStream outFromFile = new FileOutputStream(output);
        ps = new PrintStream(outFromFile);


        // NEED TO CHECK IF DATA IS ACCEPTABLE & TO STORE IN ARRAY

        while((input = br.readLine()) != null) { // reads from input.txt
            // if data is all integers, it's ok {
            //     create empty array length of input
            //     iLength = input.length();
            //     read digits, stop at spaces, and store into array
            //     printArray();
            // } // END if
            // else error {
            //     display error message
            //     exit
            // } // END else
        } // END while
    } // END readData()


/*
 * printArray --- Prints the data read from "input.txt" to another file called "output.txt".
 */

    public void printArray() {

        int[] arrayToStoreData = new int[iLength]; // create an array the same size as input length

        for(int i=0; i<iLength; i++) {
            if(arrayToStoreData[i] != null) { // this line is giving errors... can't use null because it's an int???
                ps.println(arrayToStoreData[i]); // writes what was read to output.txt
            } // END if
        } // END for

    } // END printArray()

 } // END class ReadInputArray
0
 
LVL 18

Expert Comment

by:armoghan
ID: 11928584
Make two arrays, One for storing the integers only and other for remembering the number of "_"
after every integer number.
This way you have an array with integers only and also you have "_", so that you can reproduce the output you require.

0
 
LVL 18

Expert Comment

by:armoghan
ID: 11928593
If you need to know how to separate the "_" and integers and how to find it use. String.split() or tokernizer


0
 
LVL 12

Expert Comment

by:Giant2
ID: 11928879
You can use even a Vector.
And use Integer instead of int.
In this manner you can have only one structure to store the datas.

Bye, Giant.

P.S.
new Integer(int) [cast from int to Integer]

yourInteger.intValue() [cast from Integer to int]
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11928985
Hi Luna,

Good to have you back :-) its been long. I'm back too ;-)

>> After I read the data from "input.txt", I want it to print an exact copy to an "output.txt".  

Just read it into a String and write it.

>> The problem is, when I store it into an array, I want to store each INDIVIDUAL int

Split it using a StringTokenizer or the split () method (which version of JDK are you using?), and then store the ints in an array or a Collection.

>> I want to implement the QuickSort function to sort the numbers

Do you know the basic quick-sort algorithm or do you want help with that too?
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11929006
Let the write-to-file and sort be two different parts. Deal with them separately.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11929010
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11929014
Breaking a String into multiple using StringTokenizer - http://www.javaalmanac.com/egs/java.util/ParseString.html

Here, you can store the tokens which you get into an array and then apply quick-sort.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11929022
So the algo. would be something like:

1. Read a string from the file (refer to the example-link I posted)

2. Maintain a reference to the string, say 'str'.

3. Write the string 'str' to the output.txt file (refer to the example-link I posted)

4. Tokenize 'str' using a StringTokenizer and store all tokens into an array.

5. Apply quick-sort: http://developer.novell.com/ndk/doc/samplecode/njcl_sample/NSIBrowser/QuickSort.java.html

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21068838.html
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11929023
To sort:

if you have an array you can use:
Arrays.sort(yourArray);

if you have a Vector (for example):
Collections.sort(yourVector);

You can even implement a your own comparator (see Arrays and Collections java doc).

Bye, Giant.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11929027
>> Arrays.sort(yourArray);
>> Collections.sort(yourVector);
>> You can even implement a your own comparator (see Arrays and Collections java doc).

Yes, but they might not implement quick-sort (which is what she wants, I guess).
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11930441
>>I was trying to store a string of ints and spaces into an array.  

There seems to be a little confusion here, since nothing is currently being stored at all

>>int[] arrayToStoreData = new int[iLength]; // create an array the same size as input length

Nothing is being currently written to the above - it's just being read from.

>>if(arrayToStoreData[i] != null) { // this line is giving errors... can't use null because it's an int???

You are correct about that. If you change it to the correct != 0 though, it will *always* be true, leaving you with nothing printed and nothing stored.

If you want to return an int[] from your input, and the input only contains single digits (as in your example) , you can do something like:


      public static int[] singleDigitsToIntArray(String s) {
            char[] chars = s.toCharArray();
            int[] result = new int[chars.length];
            for(int i = 0;i < chars.length;i++) {
                  char c = chars[i];
                  result[i] = (c == ' ')? 0 : c - '0';
            }
    return result;
      }
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11930547
But CEHJ, that method puts all of them into the array (either the number or a 0). It won't be possible to differentiatle between a real 0 and a blank-space that way.

>> when I store it into an array, I want to store each INDIVIDUAL int

So I guess only the individual ints need to be stored, and the blanks can be totally ignored (that c - '0' conversion is not needed).

:-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11930694
>>But CEHJ ...

I'm looking at luna621's ascii art. It clearly shows that 'something' is in the array corresponding to the space in the String. Of course the array has to have *some* kind of value in these places. What luna621 wants is up to him/her. The spaces could just as well be represented by Integer.MIN_VALUE
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11930973
>> the array has to have *some* kind of value in these places

That's exactly where I guess her approach is incorrect ;-)

Think of it.... why would you like to have so many Integer.MIN_VALUE's or 0'or something like that while sorting that array? If I look at it from a third person's point of view, the file contains numbers separated by blanks and one would want to sort those numbers. So while putting them into an array, the blanks are not required. Perhaps the blanks are merely to demarcate the numbers. Whether the demarcator is one blank-space or 2 blank-spaces or a new-line or whatever :) is immaterial.

Luna, its unlike you to be so quiet for so long ;-) you're generally the most active one on your questions ;-) can we have some clarification on what were discussing?
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11931074
>> That's exactly where I guess her approach is incorrect ;-)

Which is also why I want her to give up that approach and instead of building over that one.... start with a fresh one like tokenizing or splitting the string read from the file into tokens separated at the blank-space :-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11931808
Well i'm not sure what the real intentions are - i read it as a kind of self-made exercise. But's let's see what luna621 has to say
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 11936255
You could also use the Integer class and a try-catch block as Giant2 might have been hinting:

//NOTE: stringArray is your array of strings
//Create a vector of integers to be sorted and later output
Vector intVec = new Vector(0);
//Create an integer to hold any values parsed from your string array
int tempInt;
//loop to go through every space on the string array
for (int c = 0; c < stringArray.length; c++){
try{
//Attempt to parse a number from the string at position c in your array
//This should throw an exception and go right into the "catch" if it encounters a blank space
tempInt = Integer.parseInt(stringArray[c]);
//If it was successfully parsed, add the number to your vector
intVec(c).addElement(new Integer(tempInt));
}
catch (NumberFormatException e){
//If it wasn't successfully parsed (i.e. if it was a space), do nothing
}
}

You should end up with a vector full of Integers. You could then do a bubble sort (it's good practice :D ) or just use Giant2's suggestion of Collections.sort(intVec).
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 11936283
Gah. I had that as array code before and left put in (c). Just make "intVec(c).addElement(new Integer(tempInt));" into "intVec.addElement(new Integer(tempInt));"
I need to proofread better. ;)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11936399
Hi luna,
just to say hello and welcome back
;°)
0
 

Author Comment

by:luna621
ID: 11938486
hi zzynx!!

Wow, I go to work and I come back and there's a bombardment of comments  :)  Sorry mayankeagle!!  I posted this right before I went to bed.

I can basically read from input.txt, and write to output.txt (this is without storing into the array or sorting).  I get confused when I need to store the ints and the spaces.

Okay, to clarify a few points.  I wanted to make the output the same format as the input.

Example:

"_" represents spaces

input.txt contains the following:

9 _ _ 3 _ 1 _ 10 _ 100 _ _  (there is a total of 5 ints and 7 spaces)

output.txt should be:

1 _ _ 3 _ 9 _ 10 _ 100 _ _ (5 ints and 7 spaces)


I have an algorithm for the quicksort function that I haven't worked on yet.  I will work on that after I get this "read-from-input-and-store-into-array" part.  Thank you for all your comments!!!
0
 

Author Comment

by:luna621
ID: 11938504
Okay, so I read about the StringTokenizer (never used this function before :)  ).  This is from the website mayankeagle put a link to:

String aString = "word1 word2 word3";
    StringTokenizer parser = new StringTokenizer(aString);
    while (parser.hasMoreTokens()) {
        processWord(parser.nextToken());
    }


So, basically in my program instead of the String aString, I'll have the read from input.txt, correct?  Now, what exactly does this code do?  Does it separate the ints from the spaces?  I guess I have to also import java util??
0
 

Author Comment

by:luna621
ID: 11938506
>> Let the write-to-file and sort be two different parts. Deal with them separately.

Yes, this is what I was planning to do.  Actually, I was going to:

1. read input & store in array
2. sort
3. write to output

Or is there a better approach?
0
 

Author Comment

by:luna621
ID: 11938518
>> which version of JDK are you using?

Java2 SDK, SE v1.4.2
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 11938544
The code reads a "token" (stuff between all whitespace characters) and processes the resulting string. And yes, I think you'll need the java.util package.
0
 
LVL 3

Expert Comment

by:CI-Ia0s
ID: 11938550
>>1. read input & store in array
>>2. sort
>>3. write to output

That's what I'd do. :) Though if you take a vector/array approach and use a built-in command (Collections.sort()/Arrays.sort()), there's no need for a separate "sort" section, as it'll only take a line or two. However, if you do a bubble sort, then that's the way to go.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11938554
>> 9 _ _ 3 _ 1 _ 10 _ 100 _ _
>> 1 _ _ 3 _ 9 _ 10 _ 100 _ _

Now that's strange ;-) you'll need to maintain all those blank spaces in order. Try something like:

int[] iArray -> 9, 3, 1, 10, 100 -> sort this array
String[] sArray -> "  ", " ", " ", " ", "  " (the spaces, in order - 2 blanks, then one blank, then one blank, and so on)

Sort the first int array using quick-sort and then construct a String as:

StringBuffer sbTemp = new StringBuffer () ;

for ( int i = 0 ; i < iArray.length ; i ++ )
{
  sbTemp.append ( iArray[i] ) ;
  sbTemp.append ( sArray[i] ) ;

}

String sFinal = sbTemp.toString () ;

Write this String to the output-file.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11938557
>> there's no need for a separate "sort" section, as it'll only take a line or two. However, if you do a bubble sort,

Luna, is it necessary for you to do a quick-sort (as you mentioned) or can you use any sort?

zzynxie, a little offline these days ?
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11938573
>> So, basically in my program instead of the String aString, I'll have the read from input.txt, correct

Yes.

>> I guess I have to also import java util

Yes.

>> Does it separate the ints from the spaces

It'll not store the spaces. It'll give you only the int-part. Since you need the spaces and you also need to store the order of the spaces, I guess its better to store the spaces in some other manner.

I understand why you were storing 0 instead of the blanks in the same array which had integers. But when you sort it, you will lose the order of the blank-spaces (which you need to maintain for the purpose of writing the output), because all 0's will come at the same place. So you should maintain the blank-spaces separately.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11938599
Try something like this:

ArrayList blanksList = new ArrayList () ;
ArrayList digitsList = new ArrayList () ;
String sInput = "...." ; // the String from the file
int len = sInput.length () ;
StringBuffer sbBlanks = new StringBuffer () ;
StringBuffer sbDigits = new StringBuffer () ;

for ( int i = 0 ; i < len ; i ++ )
{
  char c = sInput.charAt ( i ) ;

  if ( c == ' ' )
  {
    sbBlanks.append ( c ) ;

    if ( sbDigits.length () > 0 )
    {
      digitsList.add ( new Integer ( sbDigits.toString () ) ) ;
      sbDigits = new StringBuffer () ;
    }
  }

  else
  {
    sbDigits.append ( c ) ;

    if ( sbBlanks.length () > 0 )
    {
      blanksList.add ( sbBlanks.toString () ) ;
      sbBlanks = new StringBuffer () ;
    }
  }

}

Now, you have the integers (as Integer objects) in the digitsList array-list and the blanks (in sequence) in the blanksList array-list. You can loop through it and get the 'int' values, then sort them using quick-sort. Refer to the links for quick-sort. Then you can finally write all of them into a String as shown in one of my previous comments.

PS: My code could have bugs. I just typed it, didn't test it. I hope you get the basic idea.
0
 

Author Comment

by:luna621
ID: 11938953
So you are using two arrays - one for the ints, and one for the spaces.  I will try this.


>> Luna, is it necessary for you to do a quick-sort (as you mentioned) or can you use any sort?

I already know how to do the others.  I just need more practice with this one  :)
0
 

Author Comment

by:luna621
ID: 11939035
Alright, I tested out this:

        ArrayList blanksList = new ArrayList(); // create new ArrayList for blanks
        ArrayList digitsList = new ArrayList(); // create new ArrayList for ints

        String sInput = "10  4 6 77    8"; // the String from the file
        int len = sInput.length(); // length of input String

        StringBuffer sbBlanks = new StringBuffer(); // create new StringBuffer for blanks
        StringBuffer sbDigits = new StringBuffer(); // create new StringBuffer for ints

        // reads through input and finds ints and spaces
        for (int i=0; i<len; i++) {
            char c = sInput.charAt(i);
            if (c==' ') {
                sbBlanks.append(c);
                if (sbDigits.length()>0) {
                    digitsList.add (new Integer(sbDigits.toString()));
                    sbDigits = new StringBuffer();
                } // END if
            } // END if

            else {
                sbDigits.append(c);
                if (sbBlanks.length()>0) {
                    blanksList.add (sbBlanks.toString());
                    sbBlanks = new StringBuffer();
                } // END if
            } // END else
            System.out.println("sbBlanks = " + sbBlanks);
            System.out.println("sbDigits = " + sbDigits);
        }// END for


This was the input String:       String sInput = "10  4 6 77    8"; // the String from the file

sbBlanks =
sbDigits = 1
sbBlanks =
sbDigits = 10
sbBlanks =
sbDigits =
sbBlanks =
sbDigits =
sbBlanks =
sbDigits = 4
sbBlanks =
sbDigits =
sbBlanks =
sbDigits = 6
sbBlanks =
sbDigits =
sbBlanks =
sbDigits = 7
sbBlanks =
sbDigits = 77    <-----  I see it got the 77 correct
sbBlanks =
sbDigits =
sbBlanks =
sbDigits =
sbBlanks =
sbDigits =
sbBlanks =
sbDigits =
sbBlanks =
sbDigits = 8

But, the spaces seem too many.  Maybe because I was doing System.out.println() so it prints every time it executes.  Should I print the Array to see what happens?
0
 

Author Comment

by:luna621
ID: 11939039
Hmm... I was thinking.  Since the ints are stored in one array, and the spaces are stored in another, do I need to combine them to make it print both?  I'm confused :(
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939097
I see:
          else {
                sbDigits.append(c);
                if (sbBlanks.length()>0) {<------------remove
                    blanksList.add (sbBlanks.toString());<------------remove
                    sbBlanks = new StringBuffer();<----------remove
                } // END if<-------------remove
            } // END else
            System.out.println("sbBlanks = " + sbBlanks);
            System.out.println("sbDigits = " + sbDigits);
        }// END for
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939105
>> Since the ints are stored in one array, and the spaces are stored in another, do I need to combine them to make it print both?

Later, yes. Try printing both the lists after the for loop and see if it gives the values correct. Terribly sorry I can't test it right now.

int iSize = digitsList.size () ;

for ( int i = 0 ; i < iSize ; i ++ )
  System.out.println ( "#" + ( ( Integer ) digitsList.get ( i ) ).intValue () + "#" ) ;

iSize = blanksList.size () ;

for ( int i = 0 ; i < iSize ; i ++ )
  System.out.println ( "#" + blanksList.get ( i ) + "#" ) ;
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939120
>> {<------------remove
>> ());<------------remove


Don't remove any of that. I found time to test the code and got the correct result. Its fine.
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939121
Try this:
            ArrayList resultList = new ArrayList(); // create new ArrayList for result
            ArrayList digitsList = new ArrayList(); // create new ArrayList for ints

            String sInput = "10  4 6 77    8"; // the String from the file
            int len = sInput.length(); // length of input String
            StringBuffer sbDigits=new StringBuffer();

            // reads through input and finds ints and spaces
            for (int i = 0; i < len; i++) {
                  char c = sInput.charAt(i);
                  if (c == ' ') {
                        resultList.add(""+c);
                        if (sbDigits.length() > 0) {
                              digitsList.add(new Integer(sbDigits.toString()));
                              resultList.add(new Integer(sbDigits.toString()));
                              sbDigits = new StringBuffer();
                        } // END if
                  } // END if

                  else {
                        sbDigits.append(c);
                  } // END else
            } // END for
            //order the ArrayList of digits (digitsList)
            Collections.sort(digitsList);
            //put the digit in the correct position for the result
            int num=0;
            for (int i=0;i<resultList.size();i++){
                  if (resultList.get(i) instanceof Integer){
                        resultList.set(i,digitsList.get(num));
                        num++;
                  }//end if
            }//end for
            //here in resultList there is the result as you want
            for (int i=0;i<resultList.size();i++){
                  System.out.println(resultList.get(i));
            }//end for


Hope this help you.

Bye, Giant.
0
 
LVL 30

Assisted Solution

by:mayankeagle
mayankeagle earned 200 total points
ID: 11939136
So once you have the two array-lists holding the values, you can get an integer-array out from the digitsList array-list:

Integer[] array = ( Integer[] ) digitsList.toArray () ;

Now you can sort this array, or you can also convert it to an 'int' array and sort it.

Once you have the sorted array, you can start the process of storing the ints and the blanks back in a String.

For that, read one integer from the sorted array and append it to the String, then read an entry from the blanksList and append it. Then, advance to the next position.
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939143
Please see my previous post.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939145
>> Collections.sort(digitsList);

Again, that's not quick-sort ;-)
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939151
The code I post before do all the things (if you want to use a different algorithm for sorting you must change only that part of code).

Bye, Giant.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939154
>> Please see my previous post.

Seen it. The code I posted before that works too :)
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939167
>> The code I post before do all the things

I didn't deny that ;-) I'd posted a different way of doing the thing (how to get the final result is posted way above), but it works :)
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 12

Expert Comment

by:Giant2
ID: 11939196
>> The code I post before do all the things

because my code do even the following:
>9 _ _ 3 _ 1 _ 10 _ 100 _ _  (there is a total of 5 ints and 7 spaces)
>output.txt should be:
>1 _ _ 3 _ 9 _ 10 _ 100 _ _ (5 ints and 7 spaces)

as luna621 ask before.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939216
Giant2, I didn't deny that it does that ;)

I suggested the same in a different manner and in broken comments instead of one. The comment which has:

>> Now that's strange ;-) you'll need to maintain all those blank spaces in order. Try something like:

tells about how to put the two arrays together after sorting and the comments of late tell how to divide the String into two arrays/ array-lists and sort them :)
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939246
I understand, mayankeagle.

luna621 doesn't say nothing, so I point his/her attention to the code. (I told "try this"). If luna621 doesn't say ok, no, or other, we only gave him/her some solution (correct or not).
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939286
I guess its sleepy-time for Luna again so we'll have to wait until a few more hours.
0
 

Author Comment

by:luna621
ID: 11939316
I tried both codes, but they seem to be missing the last digit, "8".  I tried changing some conditions like i<=iSize or sbDigits.length()>=0, but it'll give me NullPointerExceptions.

digitsList size = 4
#10#
#4#
#6#
#77#  
       <------ 8 is missing
blanksList size = 4
#  #
# #
# #
#    # <---- there's an extra blank space here
0
 

Author Comment

by:luna621
ID: 11939322
>> I guess its sleepy-time for Luna again so we'll have to wait until a few more hours.

Sorry, I was trying to install Microsoft SQL Sever 2000.  That took awhile   -_-
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939337
Ok.(<------ 8 is missing)
Replace this:
            // reads through input and finds ints and spaces
            for (int i = 0; i < len; i++) {
                  char c = sInput.charAt(i);
                  if (c == ' ') {
                        resultList.add(""+c);
                        if (sbDigits.length() > 0) {
                              digitsList.add(new Integer(sbDigits.toString()));
                              resultList.add(new Integer(sbDigits.toString()));
                              sbDigits = new StringBuffer();
                        } // END if
                  } // END if

                  else {
                        sbDigits.append(c);
                  } // END else
            } // END for
            if (sbDigits.length()>0){
                  digitsList.add(new Integer(sbDigits.toString()));
                  resultList.add(new Integer(sbDigits.toString()));
                  sbDigits = new StringBuffer();
            }
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939353
The things I do is to append:
       if (sbDigits.length()>0){
               digitsList.add(new Integer(sbDigits.toString()));
               resultList.add(new Integer(sbDigits.toString()));
               sbDigits = new StringBuffer();
          }
at the end of the for cicle, because if the last is a number it is not included during the for cicle.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939373
>> I tried both codes, but they seem to be missing the last digit, "8".

In my code, you could try this after the for loop:

} // end for

if ( sbDigits.length () > 0 )
  digitsList.add ( new Integer ( sbDigits.toString () ) ) ;

if ( sbBlanks.length () > 0 )
  blanksList.add ( sbBlanks.toString () ) ;

Does that display all values?

>> Sorry, I was trying to install Microsoft SQL Sever 2000

I was wondering. What time is it for you?
0
 

Author Comment

by:luna621
ID: 11939380
So... what you did was you still want to print (sbDigits.length()>0) even though it's not if (c == ' ').  Okay, I see that.

_ 10_ _ 4_ 6_ 77_ _ _ 8
^
that space should go  ^

10_ _ 4_ 6 _ 77_ _ _ _ 8

Let me tinker around with this, so I can understand.  Remind me never to put off java during the summer.  :)
0
 

Author Comment

by:luna621
ID: 11939401
>> In my code, you could try this after the for loop... Does that display all values?

Yes, now I have to figure out how to append (I guess is the word), or perhaps join the two together.



>> I was wondering. What time is it for you?

It is currently 9:08 pm  (HST)
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939410
>> So... what you did was you still want to print (sbDigits.length()>0) even though it's not

Just checked if there are any digits left in the buffer. If yes, then its the last number which did not get added to the array-list. So I added it again.

>> that space should go  ^

I didn't get that..... my code or Giant2's?

>> Remind me never to put off java during the summer.

Sure ;-)
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939417
>> Yes,

Ah :-)
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939425
>join the two together.

I resolved this in my code (posted before)
0
 

Author Comment

by:luna621
ID: 11939429
>>>> that space should go  ^
>>I didn't get that..... my code or Giant2's?

I'm sorry, that was Giant2's code.  I'm still trying to figure out how to combine sbDigits and the sbBlanks into one ArrayList.  Do I need to create another ArrayList resultList = new ArrayList() ??
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939434
>> now I have to figure out how to append (I guess is the word),

Look at the code I posted above. The one which has:

>> Now that's strange ;-) you'll need to maintain all those blank spaces in order.
0
 

Author Comment

by:luna621
ID: 11939437
>>>join the two together.
>>I resolved this in my code (posted before)

Sorry!!  I'll label whose code I'm refering to next time.  That was mayankeagle's.
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939445
>Do I need to create another ArrayList resultList = new ArrayList()

The combination is allready done.
I execute the code I post before and gave aas result:
 4  6 8 10   77

Is it this what you want?
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939449
Luna, if you're going by my code, then you have two Array-lists:

digitsList - contains all numbers
blanksList - contains all blanks

Take digitsList. Now convert it to an Integer array:

Integer[] array = ( Integer [] ) digitsList.toArray () ;

Now sort this array using quick-sort. Then, you can do this:

StringBuffer sbResult = new StringBuffer () ;

for ( int i = 0 ; i < array.length ; i ++ )
{
  sbResult.append ( array[i].intValue () ) ;
  sbResult.append ( blanksList.get ( i ) ) ;

}

String sFinalResult = sbResult.toString () ;
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939454
>> String sFinalResult = sbResult.toString () ;

sFinalResult would be the final String to write to the file.
0
 

Author Comment

by:luna621
ID: 11939456
Comment from mayankeagle
Date: 08/30/2004 09:15PM HST

>>Look at the code I posted above.

Ack!  I'm sorry!  My brain must still be on summer vacation mode.  Okay, I promise I'll focus from now on :)
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939474
>> sFinalResult would be the final String to write to the file.

It should be of the form:

10_ _ 4_ 6 _ 77_ _ _ _ 8 (if you don't sort the array)

Or:

4_ _6_ 8 _ 10_ _ _ _ 77 (if you sort the array)
0
 
LVL 12

Accepted Solution

by:
Giant2 earned 300 total points
ID: 11939477
I'm Giant2.
This code goes (I repeat the post), I try it.
The only things you must do is to try it. If you don't want to do this, I can only say to you Goodbye, Giant.

            ArrayList resultList = new ArrayList(); // create new ArrayList for result
            ArrayList digitsList = new ArrayList(); // create new ArrayList for ints

            String sInput = "10  4 6 77    8"; // the String from the file
            int len = sInput.length(); // length of input String
            StringBuffer sbDigits=new StringBuffer();

            // reads through input and finds ints and spaces
            for (int i = 0; i < len; i++) {
                  char c = sInput.charAt(i);
                  if (c == ' ') {
                        resultList.add(""+c);
                        if (sbDigits.length() > 0) {
                              digitsList.add(new Integer(sbDigits.toString()));
                              resultList.add(new Integer(sbDigits.toString()));
                              sbDigits = new StringBuffer();
                        } // END if
                  } // END if

                  else {
                        sbDigits.append(c);
                  } // END else
            } // END for
            if (sbDigits.length()>0){
                  digitsList.add(new Integer(sbDigits.toString()));
                  resultList.add(new Integer(sbDigits.toString()));
                  sbDigits = new StringBuffer();
            }
            //order the ArrayList of digits (digitsList)
            Collections.sort(digitsList);
            //put the digit in the correct position for the result
            int num=0;
            for (int i=0;i<resultList.size();i++){
                  if (resultList.get(i) instanceof Integer){
                        resultList.set(i,digitsList.get(num));
                        num++;
                  }//end if
            }//end for
            //here in resultList there is the result as you want
            for (int i=0;i<resultList.size();i++){
                  System.out.print(resultList.get(i));
            }
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939483
>> I can only say to you Goodbye

Come on ;-) give her some time to try both the codes.
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939490
This is the output of my code (Giant2):
4  6 8 10    77
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939501
>give her

How you know luna621 is female? In the profile there isn't.

>some time to try both the codes.

The only thing she/he must do with my code (Giant2) is to copy/paste/compile/execute
0
 

Author Comment

by:luna621
ID: 11939502
Giant2, are you feeling unloved?  I'm sorry!!  I tried it, and it works!!  Thank you for your comments.  Now I just need to implement the quicksort function (which I can do myself, I hope :P )  

Please hold while I try out mayankeagle's code.
0
 

Author Comment

by:luna621
ID: 11939514
>> How you know luna621 is female? In the profile there isn't.

There's a profile?  Anyways, mayankeagle asked me in another one of my posts.  (I'm a girl, btw)


>> The only thing she/he must do with my code (Giant2) is to copy/paste/compile/execute

Yes, but I also need time to "see" what you did, and "understand" how you came about that conclusion.  Maybe because I'm a girl, it takes more time for information to sink in... or it could be because summer just ended.  I apologize Giant2.
0
 

Author Comment

by:luna621
ID: 11939520
I just checked the profile, and it says I'm female.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939524
>> How you know luna621 is female?

From her many old questions which zzynx and I are used to :-)

>> The only thing she/he must do with my code (Giant2) is to copy/paste/compile/execute

Well, she could do that with mine too ;-) and I posted it before yours ;-) but the aim is to make her understand, which is why I am posting it in different comments (steps) and briefly stating the algo.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939534
>> I just checked the profile, and it says I'm female.

Probably not visible to others but visible only to you. You might not have checked the check-box:

>> Privacy  Display my Personal Settings

in your profile.
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939543
Ok. Don't worry. I point your attention because the solution I post was ready to use (without spending anymore time).

>I just checked the profile, and it says I'm female.
But this information is not public and noone out you can see it.

I'm happy you find (at least) now the solution.

Bye, Giant.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939544
Will be back shortly after lunch. If you have any questions regarding the algo, post them in.
0
 

Author Comment

by:luna621
ID: 11939572
>> Privacy  Display my Personal Settings (mayankeagle)
>> But this information is not public and noone out you can see it. (Giant2)

            Okay, fixed.  I never realized it was off.  Oh well.    o_0


>> I'm happy you find (at least) now the solution. (Giant2)

           Thank you, I have found a new friend!!  I will now spend the next 3 hours understanding your code and trying
           to understand it.  I hate it when people just copy & paste w/o understanding.  What's the point of learning this
           stuff if you can't grasp the concept?  :)


>> Will be back shortly after lunch. If you have any questions regarding the algo, post them in. (mayankeagle)

           Have a good lunch!
0
 

Author Comment

by:luna621
ID: 11939576
Ah, this code isn't complete yet but I figure I can tryout the rest myself.  Points time!!  Thank you again!! :)  :)  :)
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939594
Thanks.
0
 

Author Comment

by:luna621
ID: 11939600
Btw, what time is it now Giant2?
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939615
cloudy 9.56 AM 31/August/2004.

:)
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11939621
I'm European (GMT).
0
 

Author Comment

by:luna621
ID: 11939641
Giant2,

I'm from Hawaii.  Well, it was nice to hear from different people.  I will now refresh my memory of java.  Thank you for taking your time to help me.


mayankeagle,

Talk to you soon!!  Thank you!!


*goodnight!!*

0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11939725
>> I will now spend the next 3 hours understanding your code and trying to understand it

I hope you didn't have problems trying to understand my code. I tried to break it across multiple comments and mention the steps I was taking.

>> this code isn't complete yet but I figure I can tryout the rest myself.

Which one? I guess the only part which is not done in my code or Giant2's code is sorting using quick-sort, for which you can refer to the links I posted.
0
 

Author Comment

by:luna621
ID: 11949343
Comment from mayankeagle

>> I hope you didn't have problems trying to understand my code. I tried to break it across multiple comments and
>> mention the steps I was taking.

            I think because you broke it down into different steps, I was able to follow it pretty well :)

>> Which one? I guess the only part which is not done in my code or Giant2's code is sorting using quick-sort, for
>> which you can refer to the links I posted.

            I was looking at Giant2's code.  But, I was tired and needed sleep so I didn't finish the code with the quicksort
            function.  I'll look at the links you posted, but I have a pretty good idea of how to do this.  If I have problems,
            you know I'll be here again with another question post.   :)


Thank you again for all your help!!
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 11949464
>> I think because you broke it down into different steps, I was able to follow it pretty well :)

Generally, you should get more used to that on EE ;) rather than plain code.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now