Results 1 to 17 of 17
  1. #1
    Simplev_v's Avatar
    Simplev_v is offline Member
    Join Date
    Sep 2009
    Location
    Malaysia
    Posts
    10
    Rep Power
    0

    Exclamation My Simple Array Does Not Work!

    why oh why doesn't this array work.. :( i am able to write things into txt file but i cant seem to delete the null value for the array.. can someone please help..

    the problem should display the whole content first, which is [1, , ,2]
    than it should display the content without the null which is [1,2]

    Java Code:
    class justtry{
        public static void main (String[] args) {
            //String[] array1 = {"1"," "," ","2"};
            int size = 4;
            String [] array1;
            array1 = new String[size];
            array1[0] = "1";
            array1[1] = " ";
            array1[2] = " ";
            array1[3] = "2";
    
    
            System.out.print("Content of array [");
    
            for (int x = 0; x < size; x++) {
                System.out.print(array1[x] + ",");
            }
    
            System.out.println("]");
    
            for (int z = 0; z < size; z++) {
                if (array1[z] == " ") {
                    array1[z]=array1[z + 1];
                    size = size - 1;
                
                }
            }
    
    
            System.out.print("Content of array [");
    
            for (int x = 0; x < size; x++) {
                System.out.print(array1[x] + ",");
            }
    
            System.out.println("]");
        }
    }
    Last edited by Fubarable; 09-06-2009 at 05:43 PM. Reason: code tags added

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    1) Please use code tags when posting code to make the code formatted and readable. I've edited your post and have added them to help you out.

    2) Avoid comparing Strings with == " " as this doesn't work well with objects. Better to use the String .equals(...) method.

    3) Changing an array as you are iterating through it is a guarantee for disaster.

    Another way consider doing this:
    • create a temp String array the same size as array1.
    • create an int tempIndex variable initialized to 0
    • iterate through array1, checking if each item trimmed is empty. If not, copy the item to the tempArray[tempIndex] and increment the tempIndex.
    • when done, create a new String array of size tempIndex.
    • Use System.arraycopy to copy the first tempIndex items in the temp array to the new final array.

  3. #3
    Simplev_v's Avatar
    Simplev_v is offline Member
    Join Date
    Sep 2009
    Location
    Malaysia
    Posts
    10
    Rep Power
    0

    Default

    Thank you for formatting my coding.. I will ensure i put the in the future.
    Thank you for ur suggestion too.. i will try it out and post my coding here shortly

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You're welcome. Myself, I'd use an ArrayList here which is like an array but can be of variable size. You can then iterate through this and remove items if you use an iterator and its remove method.

    Oh, and welcome to the forum!

  5. #5
    Simplev_v's Avatar
    Simplev_v is offline Member
    Join Date
    Sep 2009
    Location
    Malaysia
    Posts
    10
    Rep Power
    0

    Default

    this is my modified code.. i haven't looked into ArrayList so i have 0 knowledge..

    i haven't attempted the array copying cause i just want to display the content so is it copy if i leave the data in the temporary array?

    but yet i cant get the "2" to be displayed :(

    Java Code:
    class justtry{
        public static void main (String[] args) {
           
            int size = 4;
            String [] array1;
            array1 = new String[size];
            array1[0] = "1";
            array1[1] = " ";
            array1[2] = " ";
            array1[3] = "2";
    
    
            System.out.print("Content of array [");
    
            for (int x = 0; x < size; x++) {
                System.out.print(array1[x] + ",");
            }
    
            System.out.println("]");
            String temp =" ";   // contains the search value
            String [] tarray1;  // temperary array
            tarray1 = new String[size];
    
            for (int z = 0; z < size; z++) {
                if (array1[z].equals(temp)) {
    
                    array1[z]=array1[z + 1];
                    size = size - 1;
                
                }
                tarray1[z] = array1[z]; // should move non null
            }                           // elements frm array1 to
                                        // tarray1
    
            System.out.print("Content of array [");
    
            for (int x = 0; x < size; x++) {
                System.out.print(tarray1[x] + " ");
            }
    
            System.out.println("]");
        }
    }

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    try this instead
    Java Code:
          String[] tempArray = new String[array1.length];
          int tempIndex = 0;  // the index for the temporary array
          for (int i = 0; i < array1.length; i++) {
             if (!array1[i].trim().isEmpty()) { // if item is not just white space
                tempArray[tempIndex] = array1[i]; // copy to temp array
                tempIndex++;  // and advance temp array's index
             }
          }
    
          // make final array and copy stuff in temp array into it.
          String[] finalArray = new String[tempIndex];  
          System.arraycopy(tempArray, 0, finalArray, 0, tempIndex);
          System.out.println(Arrays.toString(finalArray));

  7. #7
    DiamondDog is offline Member
    Join Date
    Aug 2009
    Posts
    18
    Rep Power
    0

    Default

    I may be misunderstanding what you're trying to do, but if you just want to display certain items in the array, and not others, couldn't you just test each item, and only display the ones you want to see?

    Something like this, maybe:

    Java Code:
    public class justtry {
    
    
        public static void main (String[] args) {
           
            int size = 4;
            String [] array1;
            array1 = new String[size];
            array1[0] = "1";
            array1[1] = " ";
            array1[2] = " ";
            array1[3] = "2";
    [COLOR="Purple"]
            // show ALL elements in the array[/COLOR]
            System.out.print("Content of array [");
    
            for (int x = 0; x < size; x++) {
                System.out.print(array1[x]);
                if(x!=size-1)
                {
                	System.out.print(","); // add a comma, except after the very last element
                }
            }
    
            System.out.println("]");
            
           [COLOR="Purple"] // now show all elements EXCEPT the search value[/COLOR]
            String temp =" ";   // contains the search value
            
            System.out.print("Content of array [");
           
            for (int z = 0; z < size; z++) {
                if (array1[z].equals(temp))
                {
                	// do nothing
                }
                else
                {
                	System.out.print(array1[z]);
    	            if(z!=size-1)
    	            {
    	            	System.out.print(","); // add a comma, except after the very last element
    	            }            	
                }
            }                                  
    
            System.out.println("]");
        }
    }
    output

    Content of array [1, , ,2]
    Content of array [1,2]
    -------------------------------------------------------------------------------
    If you wanted to use ArrayLists, you could maybe try something like this:

    Java Code:
    import java.util.ArrayList;
    
    public class justtry {
    
        public static void main (String[] args) {
           
            ArrayList array1;
            array1 = new ArrayList();
            array1.add("1");
            array1.add(" ");
            array1.add(" ");        
            array1.add("2");
    [COLOR="Purple"]
            // show ALL elements in the array list[/COLOR]
            System.out.print("Content of array list [");
    
            int listSize = array1.size();[COLOR="Purple"] // how many elements in the ArrayList?[/COLOR]
            
            for (int x = 0; x < listSize; x++) {
                System.out.print(array1.get(x));
                if(x!=listSize-1)
                {
                	System.out.print(","); [COLOR="Purple"]// add a comma, except after the very last element[/COLOR]
                }
            }
    
            System.out.println("]");
            
          [COLOR="Purple"]  // create a second ArrayList[/COLOR]
            ArrayList culledArrayList = new ArrayList();
            
           [COLOR="Purple"] // any element in the original list which is NOT the search value
            // is added to this second ArrayList[/COLOR]
            String temp =" ";   [COLOR="Purple"]// contains the search value[/COLOR]       
            
            for(int i = 0; i<array1.size(); i++)
            {
            	if(array1.get(i).equals(temp))
            	{
            		[COLOR="Purple"]// do nothing[/COLOR]
            	}
            	else
            	{
            		culledArrayList.add(array1.get(i));
            	}
      	
            }
            
          [COLOR="Purple"]  // now show the contents of editedArrayList[/COLOR]
            
            System.out.print("Contents of culled array list[");
           
            listSize = culledArrayList.size();
            for (int z = 0; z<listSize; z++) {
            	System.out.print(culledArrayList.get(z));
            	if(z<listSize-1)
            	{
            		System.out.print(","); [COLOR="Purple"]// add a comma, except after the very last element[/COLOR]
            	}
            }                                  
    
            System.out.println("]");
        }
        
    }
    output

    Content of array list [1, , ,2]
    Contents of culled array list[1,2]
    Last edited by DiamondDog; 09-06-2009 at 08:05 PM.

  8. #8
    munish is offline Member
    Join Date
    Jul 2009
    Posts
    37
    Rep Power
    0

    Default

    he if u just want to sort your array................then
    Java Code:
    class justtry{
        public static void main (String[] args)throws Exception {
            int size = 4;
            String [] array1;
            array1 = new String[size];
            array1[0] = "1";
            array1[1] = "r";
            array1[2] = "r";
            array1[3] = "2";
    
    
            System.out.print("Content of array [");
    
            for (int x = 0; x < size; x++) {
                System.out.print(array1[x] + ",");
            }
    
            System.out.println("]");
    		String ad="";
    		int st=size;
            for (int z = 0; z <=(size+1)/2; z++) {
                if (array1[z].equals("r")) {
    				ad=array1[z];
    				//System.out.println("the size value "+size+"\t"+(size-z)+"\t"+z+"\n");
                    array1[z]=array1[size-z];
    				array1[size-z]=ad;
    //take st=size as by decreasing size will change the value of size-z from 4 to 3.
    				//st=st-1; remove comments u get ur result.
    				
                }
            }
         System.out.print("Content of array [");
    
            for (int x = 0; x < st; x++) {
                System.out.print(array1[x] + ",");
            }
    
            System.out.println("]");
        }
    }
    output is [1,2,r,r,]

  9. #9
    Simplev_v's Avatar
    Simplev_v is offline Member
    Join Date
    Sep 2009
    Location
    Malaysia
    Posts
    10
    Rep Power
    0

    Default

    Thank you so much everyone.. Thank you for the ArrayList example too..

  10. #10
    Simplev_v's Avatar
    Simplev_v is offline Member
    Join Date
    Sep 2009
    Location
    Malaysia
    Posts
    10
    Rep Power
    0

    Default

    i just read that most java programme must be divided into classes with methods calling each other.

    but is it really important to have it in such way? what difference would it make, for example, by using my array programme into class with constructors?

    i find using classes are confusing cause i get lost as to what is executed 1st or in what sequence.

  11. #11
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    The reason is this: If you have a program that is thousands of lines long, it does not make sense to make it all one huge document. Its impossible to manage.

    Dividing programs into classes and having accessor methods is one of the principles of Object Oriented Design (OOD), which is the basis of Java's structure, so in short, yes you should divide programs into meaningful parts (classes).

    That being said, for small programs and quick hacks, it does not make sense to spend all the time required to implement proper OOD. As a student, you should learn these principles anyway and be prepared to implement them in the future when programs get big or you get into software engineering.

    Imagine if all of Photoshop was written as a single object... thousands of pages. You can see why Object style design is preferable.

    The key is to know when to divide. In the same way that a new student might be tempted to do everything on one page, its easy to over-divide as well. I think of it this way. If this was a machine I was building in real life, how would I divide it?

    Think of a car... Are the engine, starter, transmission, steering, suspension, seats, radio, windshield, tires, etc... all one big part? No! They are all separate systems, each of which performs a specific job, which are then bolted together. Programing is exactly the same.

    If you were making a program that downloads data from the net, searches for useful information in that data, draws graphs and then prints it out, it would make sense to make an object for each one of those tasks and then tie them together. Its the divide and conquer principle. Its much easier to work on one small subsystem at a time than to try and envision the whole machine at once.

    Even an engine has many smaller subsystems, and engineers only worry about one major part at a time. Food for thought :D
    Last edited by quad64bit; 09-07-2009 at 06:21 AM.

  12. #12
    Simplev_v's Avatar
    Simplev_v is offline Member
    Join Date
    Sep 2009
    Location
    Malaysia
    Posts
    10
    Rep Power
    0

    Default

    yes it makes sense.. it guess its like doing calculation where we solve it part by part. can i even convert my array programme into classe? i have till now learned java by writing out the whole programme as a chuck. is there any pointers on how i know where to class than?

    if i were to use the array example to make class, can i have one more class (besides the main class) just to initialize the array and than put everything else in the main class?

    something like:
    Java Code:
    class MyArray {
       String[] a;
       public MyArray (int size) {
          a = new String[size];
       }
    }
    
    class MyArrayApp {
       MyArray arr;
       arr = new MyArray(6);
    
       arr[1] = "1"
    .
    .
    .

  13. #13
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    I think for this program to avoid confusion, you can safely leave it as a single lump.
    However, why not write a new program just for fun that models an addressbook or recipe list or something?

    You could have a person class which only contains data and methods pertaining to a person. Then you could make an AddressBook class which contains a collection of people and methods for printing, searching, adding and deleting people objects from the addressbook.

    Recipes or parts lists would work the same way -- you could have ingredient classes and dish classes which contain ingredients. Get creative and start small. You'll do fine :D

  14. #14
    Simplev_v's Avatar
    Simplev_v is offline Member
    Join Date
    Sep 2009
    Location
    Malaysia
    Posts
    10
    Rep Power
    0

    Default

    besides addressbook, i can also do a employee database, rite?

    i have been trying the coding below. i want to save employee information into a text file than i want to display the saved data based on maybe salary or date joined.


    Java Code:
    import java.io.*;
    
    class temp2
    {
        public static void main (String[] args) throws java.io.IOException
        {
            char nextChar;
            String outputFileName;
    
            BufferedReader inStream = new BufferedReader(new InputStreamReader(System.in));
    
            System.out.print("Enter ouput file name");
            System.out.flush();
            outputFileName = inStream.readLine();
    
            File outFile = new File(outputFileName);
    
            if (!outFile.exists() || outFile.canWrite())
            {
                BufferedWriter bufferedoutStream = new BufferedWriter (new FileWriter(outFile));
    
                System.out.println("Enter IDNO:");
                //System.out.flush();
                bufferedoutStream.write(inStream.readLine());
    
                System.out.println("Enter FULL NAME:");
               // System.out.flush();
                bufferedoutStream.write(inStream.readLine());
    
                System.out.println("Enter BASIC SALARY:");
                //System.out.flush();
                bufferedoutStream.write(inStream.readLine());
    
                System.out.print("Enter DEPARTMENT:");
                //System.out.flush();
                bufferedoutStream.write(inStream.readLine());
    
                System.out.print("Enter DATE JOIN:");
                //System.out.flush();
                bufferedoutStream.write(inStream.readLine());
    
                bufferedoutStream.close();
    
            }
            else
            {
                System.out.println("cannot write");
    
            }
            }
        }

  15. #15
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Employee database is perfect. Make an Employee class that contains all info pertinent to an Employee, along with methods to access it. Then you can make an EmployeeDatabase class which contains an array of employees. Perfect example -- your above code looks about right too. Have you tested it yet?

  16. #16
    Simplev_v's Avatar
    Simplev_v is offline Member
    Join Date
    Sep 2009
    Location
    Malaysia
    Posts
    10
    Rep Power
    0

    Default

    yes i have tested it. it can work. it can write to the text file.
    i am actually trying to do it in a way where i can enter more than 1 record at a time. maybe when i press enter without entering ID no than it exits the program.

    but i read in the net that "print" is better than the buffered way to get input. so am a bit confused currently.

    this is actually one my assign question that i did not do than cause i spent too much time on the others and didn't have time to complete it. so am trying it now.

  17. #17
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    I use the method you use to get input. There are several other ways to do it, but this is still my favorite.
    For input/output from a file, I use:
    Java Code:
    BufferedReader in = new BufferedReader(new FileReader(new File("myFile.txt")));
    BufferedWriter out = new BufferedWriter(new FileWriter(new File("myFile.txt)));
    You can also use a PrintWriter for output -- this is especially great for client/server apps, since it flushes the stream automatically. For file output, I like to be able to control what happens.

Similar Threads

  1. New simple application using a simple database
    By webbusiness23 in forum New To Java
    Replies: 9
    Last Post: 08-03-2009, 03:55 AM
  2. Simple animation won't work
    By nolsen01 in forum New To Java
    Replies: 4
    Last Post: 07-09-2009, 12:36 AM
  3. Replies: 5
    Last Post: 02-25-2009, 08:14 PM
  4. Simple array questions
    By jigglywiggly in forum New To Java
    Replies: 6
    Last Post: 02-15-2009, 06:57 AM
  5. Replies: 2
    Last Post: 05-04-2008, 06:27 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •