write to file in loop, help please--java
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: write to file in loop, help please--java

Hybrid View

  1. #1
    Join Date
    Jan 2013
    Posts
    20

    write to file in loop, help please--java

    Can anyone help me please, I cant figure out what I am doing wrong or missing. I need to enter a sentence and write it to a file over and over again until the word done is typed then it should exit the program. please help

    Code:
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    
    public class StringtoFile {
    	
    	public static void main(String[] args) throws IOException
    	{
    		StringtoFile h = new StringtoFile ();
    		
    		h.openFile();
    		h.addline();
    		h.closefile();
    	}	
    	private Scanner scan, X;
    	
    	 	public void openFile(){
    	 		try{
    			 	 X = new Scanner(new File("testFile.txt"));
    	 			}
    	 		catch(Exception e){
    			 System.out.println("You received and Error");
    			 
    	 		}
    	 		}
    	
    	 	public void addline(){				
    	
    	 		System.out.println("Enter a Sentence.....");
    			String str, casefinish = "done";
    				str = X.nextLine();
    		
    	if(casefinish.equalsIgnoreCase("done")){
    		//break;
    	}
    		else{
    			while (str!="done");	
    				str = X.nextLine();
    	}	
    	}
    	
    	public void closefile(){
    		X.close();
    	}
    }

  2. #2
    Join Date
    Aug 2011
    Location
    West Yorkshire, U.K.
    Posts
    54

    Re: write to file in loop, help please--java

    OK ... you need a "buffer" to hold the input and loop which repeatedly asks for input and either (1) adds this to the buffer or (2) exits when the input is "done". Something like ...
    Code:
    StringBuffer buf = new StringBuffer();
    while(true) {
      print "Enter a sentence"
      read input into variable (str in your case)
      if(str.equalsIgnoreCase("done")) {
        break;
      }
      buf.append(str)
    } // end of while
    So what happens is the system will prompt "enter a sentence". Input is checked and if it is "done", the "break" statement exits the while loop. Otherwise the input is appended to the buffer and the loop resumes, prompting for another sentence.
    Once the while loop has exited, the buffer is still in scope, so you can then use buf.toString() to print out the contents of the buffer or write to a file etc.
    Generally, you should not compare strings using == [e.g. if (String1 == String2) ], you should use .equals or .equalsIgnoreCase [e.g if (String1.equalsIgnoreCase(String2) ].

  3. #3
    Join Date
    Jan 2013
    Posts
    20

    Re: write to file in loop, help please--java

    Thank you for your help Alex. I finished the code and it looks like the following....
    can you look at it and recommend any changes that might help my coding technique?

    Code:
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    
     public class StringtoFileException {  
    
         String file=new String("UserStrings.dat");  
    
         FileWriter fileStream = null ;    
    
            
    
                {try {    
    
                  fileStream   = new FileWriter(file);    
    
                     }   
    
                catch (FileNotFoundException e) {    
    
                   System.out.println("file error, problem with name of File, Check your file name");  
    
                     }   
    
                catch (IOException e) {  
    
                        e.printStackTrace();  
             }  
    
        
         }
      
         
          
            
    
         public static void main(String[] args) throws FileNotFoundException 
    
         		{  
        	 			StringtoFileException h = new StringtoFileException ();  
        	 			h.openFile();
    					h.addline();  
        	 			try {
    						h.closefile();
    					} catch (IOException e) {
    						e.printStackTrace();
    					}
    					
        	 			 
         		}     
    
         
         private Scanner scan, X;     
    
         
         public void openFile() throws FileNotFoundException
         		{ 
        	 try{
         		
        	 X = new Scanner(file);
        	 }
       
        	catch(Exception e){  
    
        	System.out.println("You received and Error on file not found");  
        	}
        	}
    
         public void addline() {    
    
             String str="initial";  
             System.out.println("Enter a Sentence....."); 
             
             while(!str.equalsIgnoreCase("done")) {  
    
               System.out.println("Enter another Sentence.....");  
    
                 Scanner in=new Scanner(System.in);            
    
                     str = in.nextLine();
                     try {  
                        	 
                             if(!str.equalsIgnoreCase("done")) 
                            	fileStream.write(str+"\n"); 
                         
                        else {
                        	 break;
                         }
                         }
                         catch (Exception e) {  
                        	 System.out.println("There was an Error");
                         }  
             		}
             }  
    
         	public void closefile() throws IOException{  
    
             X.close();  
             fileStream.close();
         	}  
     	}

  4. #4
    Join Date
    Aug 2011
    Location
    West Yorkshire, U.K.
    Posts
    54

    Re: write to file in loop, help please--java

    You have some code which more or less works, but is not pretty in its function or its presentation.
    Indentation is seemingly random with a mixture of tabs and spaces - try to stick to one or the other. My preference is 4 spaces and to avoid tabs altogether because then code formatting is maintained in whatever editor or IDE chosen to view the code.
    Indentation increases readability and makes it easier to spot where functions, if-then statements, loops, try-catch statements begin and end.
    You open your output file in a static block of code. This is not good because every time this class is instantiated, it will open a file.
    String file=new String("UserStrings.dat"); could be replaced with String file = "UserStrings.dat";
    Variable scan is never used.
    X is a scanner which is never used.
    Should try to use more meaningful names than X and h
    You create a new scanner "in" every time the loop gets executed. Create it before the loop and close it after the loop completes. Addline only needs to test the contents of the string once - simply ordering the statements more logically makes it look and function better. i.e.
    Code:
        public void addline() {
            Scanner inScanner = new Scanner(System.in);
            String inputStr;
            System.out.println("Enter a Sentence.....");
    
            while(true) {
                inputStr = inScanner.nextLine();
                if(inputStr.equalsIgnoreCase("done")) {
                    break;
                }
                try {
                    fileStream.write(inputStr + "\n");
                }
                catch (IOException ex) {
                    System.out.println("There was an Error: " + ex);
                    break;
                }
                System.out.println("Enter another Sentence.....");
            }
    
            inScanner.close();
        }
    Your use of try-catch is inconsistent. I would re-throw exceptions in openfile and closefile - to let them terminate the program. I would catch the ioexception in addline and use it to exit the loop.

Tags for this Thread

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center