Java loop question - I think!

Hello,
I currently have the below code which opens a file, reads all the contents and prints it. I would like to modify it such that it the searches the file for a particular word e.g. "from" and when it reaches it, it inserts something after it e.g. "me". I think I need to put a nested loop somewhere in my while loop. Can some advise me please?
Many thanks,
Aisling.
void modifyFile (String username)
String record = null;
int recCount = 0;
try {
FileReader fr = new FileReader("/tmp/Scripts/Script.xml");
BufferedReader br = new BufferedReader(fr);
record = new String();
while ( (record = br.readLine()) != null) {
recCount++;
System.out.println(recCount + ": " + record);
catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}

I tried the replaceall suggestion but it still does not work. I have included my effort below -
Any ideas why it wont work?
My understanding is that the below code reads a file line by line. As long as the line isnt null(i.e. end of file), the contents of the file should be printed and any instances of "from" should be replaced with the variable username. This is then written back to the file. Correct?
Thanks again,
Aisling.
void modifyFile (String username)
String record = null;
int recCount = 0;
try {
FileReader fr = new FileReader("/tmp/Scripts/Script.xml");
BufferedReader br = new BufferedReader(fr);
record = new String();
while ( (record = br.readLine()) != null) {
recCount++;
record.replaceAll("from", username);
System.out.println(recCount + ": " + record);
FileWriter fw = new FileWriter ("/tmp/Scripts/Script.xml");
fw.write(record);
catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("Uh oh, got an IOException error!");
e.printStackTrace();
}

Similar Messages

  • Java "loops" Stopped working

    I am a new Mac user (as of June 9) with the new MacBook Pro. A website that I access frequently that uses Java loops suddenly stopped working 3 days ago. I did not change anything..The only thing I can think of is that an automatic SW update changed something..I checked the Java preferences and the last change date was June 25, so it would appear nothing with Java changed recently..The only thing that was downloaded recently was QuickTIme R7..Is there some compatibility issue? I was going to try to uninstall the new QuickTime but I do not know if that is possible and if it is, can someone tell me how to do this? I know how to install/uninstall programs on WinXP, but obviously this is Mac 10.5.7 and I do not want to mess things up! Any suggestions on how to resolve or debug would be much appreciatged! Thanks in advance.

    Using Mac OS X and Internet/Networking:
    http://discussions.apple.com/category.jspa?categoryID=235
    TimeMachine and bootable backups are a must. Make a clone of your boot drive and then keep it off line. Mac OS X can boot from multiple drives with same OS, including external drives.
    That way, you can boot from your last month backup and test to see if it still happens.

  • Question: I think I made mistakes using several different id apple. How can I cancel all of them except the one I would like to maintain ?

    Question: I think I made mistakes using several different id apple. How can I cancel all of them except the one I would like to maintain ?

    From Here   http://support.apple.com/kb/HE37
    I have multiple Apple IDs. Is there a way for me to merge them into a single Apple ID?
    Apple IDs cannot be merged. You should use your preferred Apple ID from now on, but you can still access your purchased items such as music, movies, or software using your other Apple IDs.

  • Flash/java remoting question

    Hi,
    i'm new to flash remoting and am finding using it with java
    quite troublesome. I've also found using the FileReference class
    troublesome if you use java. my question is can you somehow tie the
    remoting functionality to the FileReference.upload method
    fucntionality??
    thanks in advance

    I will use the program with photo detector to test
    the response time of the LCD screenWhy Java?I second that. With a test like that, you want to reduce the experiment down to a single variable, in this case the lcd response time. Using a java program to feed the monitor input introduces a second variable, the response time of the program. The java program's timer may not be exact, the components may not be repainted completely quickly enough, etc. If this is just for your own amusement, maybe that doesn't matter, but if you want your results to have any reliability, you'll need a more accurate and controllable input source.

  • Quick Easy Question- I think...

    If you have 15 expressions, concatenated by Boolean OR's, how many of the expressions must be true for the entire thing to be true? My friend and I are arguing whether the answer is...
    a. at least 1
    b. all of them
    c. cannot be determined
    Thank you so much for your input. We are studying for an exam, trying to finish the practice questions. I appreciate any input and your time!! :-)

    Hi,
    Programming languages are created by humans, and therefore it is usually pretty easy to answer such questions. Think about the human language..
    Do you have a car or a house or a space ship?
    Any one who owns a car or a house would answer yes, even if they didn't own a space ship. That is, the whole expression evaluates to true if one of the statements is true.
    /Kaj

  • Can I post here(Acrobat Windows) Java Script questions here?

    Hello
    Can I post here(Acrobat Windows) Java Script questions here? If not, wht is the correct forum?
    THank you

    Back up and down to Acrobat Scripting. Bot Windows and MacIntosh Acrobat versions use the same JavaScript.
    If you are using LIVECYCLE DESIGNER use their forums. The JavaScript syntax and objects are different in LIVECYCLE DESIGNER!

  • Java/HTML/Loop Question

    Hiya,
    I wasn't too sure where I should post this so let me know if its in the right place.
    Basically I am completing an online voting system using servlets. I have all the features working correctly except for one. I am totally dumstruck as to what I should put in the below ****** gap.
      out.println("<form name = vote action=ballotServlet method= POST>" +
                                "<TABLE border = 1 cellspacing = 3>" +
                                "<tr><th>Name</th><th>Description</th><th>Party</th><th></th></tr>");
                        ArrayList all = c.allCandidates;
                        for (int i = 0; i < all.size(); i++) {
                            Candidate value = (Candidate) all.get(i);
                            out.println("<tr><td>" + value.getName() + "</td>" +
                                    "<td>" + value.getDescription() + "</td>" +
                                    "<td>" + value.getParty() + "</td>" +
                                    "<td><input type=radio name=vote value= ****** ></td></tr>");
                        out.println("</TABLE>" +
                                "<p><input type=submit id=submitVote value=Submit Vote>" +
                                "</BODY></HTML>");
                        out.close();Basically, I need the value from whatever is produced in that loop (the value of the radio button) but if I assign it to a value such as value.getName..it just reads it out as this String rather than the actual value. I have tried to assign it to a seperate value also but it just doesn't work.
    Does anyone have any ideas?
    Thanks,
    welsh-diva87

    I'm not sure this is something we can answer for you. It's a design decision. You seem to be asking "How can I identify which candidate was selected when the form gets posted back to the server?"
    This identifier is whatever you want it to be. It should be some unique value for each candidate in your list, and something that won't cause problems when being URLEncoded. The name may work, in which case you could put value.getName() in your space. If that doesn't meet your needs, then use something else, even an arbitrary id string for each candidate.
    Btw, the HTML you are generating is very wrong. Your attribute values need to have quotes around them in the response. If you're in java code you could print it like this:
    out.println("<form name=\"vote\" action=\"ballotServlet\" ...{code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Infinite Loop Question - should be simple

    Ok I think I have a simple question to ask here. I am attempting to create a program that creates an infinite loop for multiples of two...
    ex: 2, 4, 8, 16, etc...
    The math behind it is simple, x^2 when x = 2. I then want the result of each equation to be squared, and infinitely.
    Here is the code Ive written so far, I think Im close, but I may be way off... any hints or clues as to my next step would be appreciated.
    public class loopytest {
       public static void main (String[] args)
       int x = x^2;
       while (x = 2)
       System.out.println("Value of x is " + x);
    }

    int x = x^2;You have to initialise "x" first.
    You should give it an actual value (e.g. 2) for this case.
    int x = 2;If you want to get the value of x from arguments. (e.g. java YouProgram 2)
    You should change this part of code similar to the follow.
    int x = args[1];But this one hasn't used the Math.pow(), you should read the API and amend it.
    while (x = 2)This one is actually assign x with value 2.
    If you want to compare an int, you should use "A == B", "A.equals(B)" for Object.

  • Apple Loops Questions

    1) Where does Logic store user-created loops that I've added to the library?
    2) What is the easiest/best way to convert a regular .aiff or .wav file into an apple loop?
    3) I'm getting a lot of artifacts when I use loops I created--even when the loop is being played back at the same tempo as the original! Is this normal? You'd think that if the original cut was 120 BPM, and I turn it into an Apple loop, and stick it into another project at 120 BPM, there should be no artifacts, right?
    4) Sometimes when I click "add to loop library" Logic won't let me select "looping" as an option. This is after I've already analyzed the cut in Apple Loops Utility. What's up with that?
    Any help, insight or guidance would be appreciated.
    Thank you!

    zgogor wrote:
    1/ apple loops folder / check them ....
    I see folders for all Apple's loops and jam packs, but nothing for my loops.
    Edit: Found them They are at:
    ~/Library/Audio/Apple Loops/User Loops
    Before I was checking the root /Library, which is why I couldn't find them.
    2/ apple loop utility application / check it ...
    I have been using it, but considering the strange behavior I'm getting (see question #3 and #4) I think I might be missing a step or doing it wrong. Right now I open an audio selection in Apple Loops Utility, fill in the tags, mess around with the transient sensitivity, then "save." So why can't I add it as a loop after that?
    3/ no of course.
    Any idea what I might be doing wrong?
    4/ add to appleloop library doesn't mean it is converted, check appleloop utilty first then add them to the Lib
    I did use the loop utility first. I mentioned that in my original post.
    Message was edited by: Zachary Conlyn
    Message was edited by: Zachary Conlyn

  • Simple java pgm - question

    Hallo,
    to the following pgm I had question:
    static void printPrimes (int max) (= wavy bracket;
    boolean(should be angular brackets) sieve = new booolean (angular br max+1
    angular br)
    int i,j;
    for (i=2; i = max;i++)sieve(angluarbr i angular br)= true
    i= 2
    while (i= <= max;) (=wavy bracket Out.println (i+ " "); // is prime
    for (j=i; j <= j+i) sieve(angular br j angularb.) = false;
    while (i <= maxAmpersandAmpersand !sieve (angular br angular br)I++;
    ) wavy br ) wavy br.
    I hope this is still kind of readable.
    Q's are:
    after the first "for" there is a new i=2, which seems to staty at 2 all the time; the following while does not change this value ( the beginning for i++ does not change this) and so seems to print 2 at all times (??)
    then the inner loop seems to count up all the doubbles of the new prime number and thrwoes it out as false at the end of it;
    the i values (increased with i++ seemsto refere at all times to the unit numbers and only indirect to the un it values, which are written/ assigned to it (??)
    I seem to wonder how the pgm can print out anythings else the 2's.
    I would appreciate any help to that.
    ml
    griz

    I hope this is still kind of readable.No, it's not. http://forum.java.sun.com/help.jspa?sec=formatting
    Why are you omitting the braces and brackets? And why don't you type "program"? Aren't we worth the additional time it takes?
    Q's are:
    after the first "for" there is a new i=2, which
    seems to staty at 2 all the time; the following
    while does not change this value Why should it? You don't tell it to.
    ( the beginning for
    i++ does not change this)It does. It just gets re-set to 2 after the for loop-
    and so seems to print 2 at
    all times (??)Yeah. What else?
    then the inner loop seems to count up all the
    doubbles of the new prime number and thrwoes it out
    as false at the end of it; That part is definitely unreadable.

  • A relatively simple question ( I think)

    I'm pretty new to java. I've read a few books and been practicing the basics, and now I'm attempting to learn a bit more through the creation of a simple game. I've been able to get a lot of the groundwork down, however, I'm having trouble figuring out just how to do one of the simple things that I need.
    This game is grid based, and each time a sprite moves it moves a uniform distance of one tile (around 20 pixels). I need to set it up, however, so that the characters don't just "pop" to each location, but that they actually use their walk animation to travel one square's worth of distance.
    I'll post the simple code I tried, along with my thoughts on why it doesn't work, and then I'd like to know if I'm just going about it all wrong, and I should try another method, or there is an error in my code. My comments in the code explain what's going on (or supossed to be).
    public void moveLeft() { //this method is called when the left arrow is pressed
        moving(); //this is a method that simply sets the sprite's animation to a walk loop and changes a couple status variables
        int x = getXPosn(); //get the current x position
        int y = getYPosn(); //get the current y position
        int newx = x - 20; //newx is where I want the sprite to end up
        for (int n = x; n > newx; n--) { 
            setPosition(n, y);
        stopLooping(); //stops the looping animation
    }Now that seems pretty straightforward to me. I set the sprite to its walking animation. I get the current position, and tell it to go 20 pixels to the left, by decrementing 1 pixel at a time. Then, when it gets there, stop looping the animation.
    However, what I end up with is the same as if the for loop is nonexistant and I just used setPosition() to "warp" the character to the new spot. The animation never takes place, and the sprite doesn't "slide" along the screen like I want. Is this because the for loop just processes so quickly from x to (x-20) that its unnoticable? And if so, how do I slow it down so that I can see this animation?
    Perhaps I'm going about it all the wrong way, and there is a better method for getting at what I want. Any help would be greatly appreciated. For what its worth, I do know the moving() method,looping, stopLooping(), setPosition(), and all of that works. When I set it so that holding down an arrow key moves the sprite, it works fine. The sprite moves around, with the walk animation as long as the key is being pressed. That's just not what I need to do here. I just want it to walk a fixed distance, with its animation, from a key press.

    well, it may have bloated my code a bit, but it works. I believe that once I get more of the game elements in place, I'll be able to simplifiy it, but I'm trying to take my time and get each part working solidly before adding more.
    //I have a method that updates my sprite's x,y position each time through the gameloop by simply doing
    locx += mx
    locy += my
    //where locx, locy is the current location and mx, my is the amount of movement (either positive or negative);
    //Then, I needed 2 methods to get it to stop when I wanted.
    public void stepLeft() {
           int x = getXPosn(); //returns the value of the current x position
           moving();
           setStep(-1,0); //this method sets the movement amount each update- (-1,0) means move left 1 pixel on the x axis each update
           moveLeft((x - 20)); //sends the value of where I want the sprite to end up when I'm finished to the other method I created
    public void moveLeft(int x) {
           while (getXPosn() > x) { //this loop runs while the x location of the sprite is greater than the location I want it to end up at.
               isStill = false; //this is just a boolean identifier
           stopMove(); //A method that just stops the looping animation and resets the movement to (0,0)
    }I tried to get it all in one method, but was having trouble, with using getXPosn() in the same method that I needed to check getXPosn() later. It kept creating infinite loops, because (getXPosn() - 20) would change based on the sprite's movement. So my workaround was to send it to another method for the loop.
    As I said, I think this is a little bloated for what the code will be when I'm finished. I need to turn my background into a grid and I'm going to define each tile at some point. Then, I can go back and alter this code so that it just checks if its going into the boundaries of a new tile, rather than needing to use so many methods.

  • Java Programming Question

    Hi,Everybody:
    I have a question about Java programming. If I want to write a java class code called if.java like below, how should I do to make it pass the java compiler and make it work. I know the words "if" and "for" are reserved words. I just try to figure it out that is it possible??? Do I need to create my own java compiler or recompiler?
    public class if
    public if() { }
    public static for test()
    return new for();
    public class for
    public for() { System.out.println("for class constructor"); }
    }

    I don't think you can bypass the compiler's rejection of this. There is little point to naming the classes after keywords. Not sure if it's case sensitive though, so maybe "If" or "For"? Otherwise, try "if_" or "for_"

  • Java Interview questions!!!!!!!!!!!!

    Hi folks,
    I had an interview with a small company a few days ago.
    Below is a list of the questions that they asked me.
    Some of these are not familiar to me at all.
    Does anyone have the answer for these?
    (1) Draw UML diagrams that express the following concepts:
    (a) Class C and class B are subclasses of class A.
    (b) Class P has two private fields int x and int y and one
    public method setXY(int x1, int y1)
    (c) bob is and object of class Bob.
    (d) Class A objects contain one or more objects of class B.
    (e) Interface A is implemented by class B and class C.
    (2) Define the following computer science terms:
    (a) Primitive type
    (b) type conversion
    (c) narrowing / widening a type.
    (d) reference type
    (e) type casting
    (3) (a) Give an example of variable shadowing.
    (b) (2pts) Explain the difference between method hiding and
    overriding methods.
    (c) Give an example of marker interface.
    (d) Suppose class A implements two interfaces C and D. Each of these
    has a method public void getRichQuick() but C's method
    throws CaughtBySECException and D's method throws
    AntitrustException. What will the compiler do?
    (4) (a) With respect to subclassing what does restriction mean?
    (b) How do we implement restriction in Java?
    (c) Suppose we have two interfaces in Java: I2 which extends
    I1. Is I2[] a subtype of Object[] ? Why or why
    not?
    (d) What is multiple inheritance?
    (e) Give a way to achieve the effect of multiple inheritance in Java.
    (5) (a) In a Java class definition what is an initialization. Give an
    example.
    (b) Give the order in which the following three things would be
    initialized when a subclass B of class A is created:
    (i) an explicit initializer in B, (ii) an explicit initializer
    in A, and (iii) an initalization statement in a constructor of A.
    (6) (a) On what methods and classes should one use /** ... */ comments?
    (b) For javadoc to detect these comments where relative to these
    methods/classes should the comment occur?
    (c) Explain how to use each of the following javadoc tags:
    (i) @since (ii) @see (iii) @param
    (7) Define the following terms with respect to their object-orientation
    meaning. Give an example of (b) and (c).
    (a) framework
    (b) idiom
    (c) design pattern
    (8) Give each of the things needed for the canonical form for public classes
    in Java.
    (9) Class A and Class B each contain identical blocks of code 30 lines long.
    Class A extends Class C and Class B extends Class D. Suggest a way to
    avoid the code duplication using factorization. What kind of
    factorization did you use?
    (10) Give the UML diagrams for the folowing design patterns:
    (a) Strategy
    (b) Iterator
    (c) Factory
    (d) Template
    (e) Singleton

    I think I can help you with a few points:
    2
    a. Primitive types are byte, short, char, int, long, float, double and boolean. They tell the compiler the type of the variable and thus how much memory needs to be set aside to store the variable in memory.
    b. Converting from one type to another which kinda links in with c. Widenening is the process of changing, for example and byte to an int (no explicit cast is needed) because a byte (8 bits) can fit into an int (32 bits).
    However the reverse is not true (obviously) so an explivit cast is needed to tell the compiler that you meant to do it (as information can be lost).
    e.g. int i = 3000;
    byte b = (byte)i;
    obviously a byte can only hold values up to 127 so converting this int to a byte changes the value. You have to look at the bits and understand a bit of binary code for this.
    This kinda answers part e. too.
    d. A reference type is a pointer to a cariable or object (I think thats what its getting at). eg int i = 32; i is a reference to the memory address where the computer stored the value 32.
    4d.e Multiple inheritance is when a subclass inherits from more than one base class. In java this is not possible (java only supports single inheritance with the extends keyword). However, java overcomes this with interfaces as a class, although it can only extends one base class, can implement as many interfaces as it likes in a comma seperated list.
    I hope this helps you on your way. The fact of the matter is, the majority of your questions can be found in any decent book on java (and UML). Also look at the java tutorial online.
    For example 1a is simply a box with two other boxes beneath with arrows pointing upwards to the base class (not downwards as would seem reasonable).
    The best way to learn all this stuff is to read it then try it yourself! That way you'll remember it much better.
    Good luck

  • Begginer`s question . i think

    Okey .. so i'm new with java but i need to find out something ..
    i'm using a java application for my mobile, a notepad to be exact.
    For it to store notes it uses a .rms file ( from what i've seen is a db of somekind ).
    I was wondering if there is a application or something to see all the entries of this .rms file from the pc and to edit them.
    Is this possible ?
    Thank you.

    Yes. About that.
    What is the reason that it's phone dependent ?
    I've seen a lot of similarities in .rms files with different records:
    The begging is the same:
    midp-rms   [?     :??wI"?9*{??????   and i think after there some variabiles that are in some connection with the file size and the number of the records
    and the separator from recordings is:
          ?       ( where ^ is variabile )
    So .. i repet my question: What is the reason that rms files are phone dependent ?

  • Eclipse java import question

    This is my first time using 3rd party open source code within one of my projects. I'm using Eclipse for development and I just imported the 3rd party project from their SVN repository. I imported the new project into my workspace. Now I need to use it in another project in Eclpse. I know I need an import statement to use it, but I'm not sure how to go about this. Any help? Do you need any more information? TIA

    Right, but since the 3rd party project is in my workspace shouldn't the import statement look like this?
    import jaudiotagger.src.org.Audio.*;
    If that is the package name. It's a very strange one, are you sure it shouldn't be just org.audio.*? Have a look in the Jar file.
    It isn't recognizing jaudiotagger at all when I try to do a ctr+space.So is it really in your workspace?
    These are really Eclipse questions, not Java questions, you would be better off at an Eclipse forum. But I think it's pretty simple to fix.

Maybe you are looking for