Getting a for loop inside a while loop

I've been having problems with the code below. I'm trying to get the 'while' loop to work so that the program will continue to run after a user types in a sentence. This is supposed to print out how many times a letter has been typed when a sentence has been put in, but it's not working right. It just keeps adding the first sentences numbers together even when a new sentence is typed out. I don't know what I'm doing wrong with this 'while' loop.
import java.util.Scanner;
import java.util.*;
public class Count
public static void main (String[] args)
String phrase; // a string of characters
int countBlank; // the number of blanks (spaces) in the phrase
int length; // the length of the phrase
int countA = 0; // the number of a's in the phrase
int countT = 0; // the number of t's in the phrase
int countE = 0;
int countS = 0;
char ch; // an individual character in the string
Scanner scan = new Scanner(System.in);
// Print a program header
System.out.println ();
System.out.println ("Character Counter");
System.out.println ();
// Read in a string and find its length
System.out.println ("Enter a sentence or phrase ('quit' to quit): ");
phrase = scan.nextLine();
length = phrase.length();
// Initialize counts
countBlank = 0;
// a while loop to allow user to keep entering phrases
   while (true)
   String line=scan.nextLine();
          System.out.println("Type quit to quit or enter a new phrase.");
     if(line.equals("quit"))
break;
// a for loop to go through the string character by character
// and count the blank spaces
for(int i = 0; i < phrase.length(); i++)
ch = phrase.charAt(i);
switch (ch)
case ' ': countBlank++;
break;
case 'a':
case 'A': countA++;
break;
case 't':
case 'T': countT++;
break;
case 'e':
case 'E': countE++;
break;
case 's':
case 'S': countS++;
break;
// Print the results
System.out.println ();
System.out.println ("Number of blank spaces: " + countBlank);
System.out.println ("Number of A's: " + countA);
System.out.println ("Number of T's: " + countT);
System.out.println ("Number of E's: " + countE);
System.out.println ("Number of S's: " + countS);
System.out.println ();
}

Ok well I don't really understand what you're saying, but here's an improved version of my code and I can get it to work, but I don't know how to turn the "do while" loop into just a "while" loop.
import java.util.Scanner;
public class Count3
     public static void main (String[] args) {
          String      phrase;           // a string of characters
          int      countBlank=0;      // the number of blanks (spaces) in the phrase
          int      length;           // the length of the phrase
          char      ch;                // an individual character in the string
          int      countA=0;       
          int      countE=0;
          int      countS=0;
          int      countT=0;
          String quit = new String("quit"); //String wasn't initialized
          Scanner scan = new Scanner(System.in);
          // Print a program header
          System.out.println ();
          System.out.println ("Character Counter");
          System.out.println ();
          do { //do-while loop
          // Read in a string and find its length
          System.out.println("Enter a sentence or phrase, or type \"quit\" to quit: ");
          phrase = scan.nextLine();
          length = phrase.length();
          // a for loop to go through the string character by character
          // and count the blank spaces, a's, e's, s', and t's
               for (int i = 0; i <= length-1; i++) {
                    ch = phrase.charAt(i);
                    switch (ch) {
                         case ' ': countBlank++;
                         break;
                         case 'a':
                         case 'A': countA++;
                         break;
                         case 'e':
                         case 'E': countE++;
                         break;
                         case 's':
                         case 'S': countS++;
                         break;
                         case 't':
                         case 'T': countT++;
                         break;
               // Print the results
               System.out.println ();
               System.out.println ("Number of blank spaces: " + countBlank);
               System.out.println ("Number of a's: " + countA);
               System.out.println ("Number of e's: " + countE);
               System.out.println ("Number of s's: " + countS);
               System.out.println ("Number of t's: " + countT);
               System.out.println ();
               countA=0; countE=0; countS=0; countT=0; countBlank=0;
          }while (!(phrase.equalsIgnoreCase(quit)));          
     }//end main
}//end class Count

Similar Messages

  • Value not getting resetted for Node inside Node

    Hi All
    I have created the node structure as below
    A (Value Node)
    |_ID (value attribute)
    |_B (Value Node)
        |__Val (Value Attribute for Node B)
    Now the code is as follows
    for(i = 0 ; i < n ; i++ ){
    Ele Aele = createElement
    Aele.setID("1")    
    nodeA.addElement(Aele)
    for(j = 0 ; j < n ; j++ ){
        Ele Bele = createElement
         Bele.setVal("Val1")
         nodeB.addElement(Bele)
    Now i want for ID - 1 , Val - a,b,c
    when sec time loop iterates
    ID - 2 , Val - d,e,f
    But the problem is that
    For ID - 1 , i am getting Val - a,b,c,d,e,f
    when sec time loop iterates
    ID - 2 , Val - a,b,c,d,e,f
    I hope you all can get what my problem is..
    Kindly comment and help me out
    Regards
    Sonal Mangla
    Message was edited by:
            Sonal Mangla

    Hi ,
    There are a lot similar posts in forum.
    You can also search help.sap.
    Try this link. They have explained creation of similar context structure.
    http://help.sap.com/saphelp_nw04/helpdata/en/13/4cde139306304480e89d815ffcf891/frameset.htm
    Regards
    Bharathwaj

  • For Loop Exit

    Hi there, i am writing a program that requires a break in the for loop. However, I am using Labview 7.1, and it doesnt have a conditional exit. If anyone can give me some suggestions, I would appreciated it. 
    Derek
    Solved!
    Go to Solution.

    You do not have to include the upper test in your loop. If you use the auto-indexing you get that for free. The while loop will run as many iterations as there are array elements (provided whatever other conditions you test to stop the loop are not met).
    The one thing to be aware of though is if you connect more that one array the number of iterations run will be equal to the size of the smallest array. If you have an empty array the loop will not run.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • I feel ashamed but would someone help me with for loops?

    Hello all,
    Firstly, apologies. I feel ashamed. I am not new to programming but new to Java, so imagine my frustration at my blatant stupidity why I can't get this for loop to work....
    public void initGame(String[] arrTemp) {
    for (int i = 0; i > 4; i++) {
    frmGameOptions.append("hello" + arrTemp[i] + "-" + txtBully);
    basically the above method does not work!
    arrTemp does contain elements, trust me!
    it seems at though the loop isn't even getting entered!
    please help me!!!!!!!!!!!!!!!
    poncenby

    i think you want
    for (int i = 0; i < 4; i++)
        frGameOptions.append("hello" + arrTemp[i] + "-" txtBully);
    a better way would be
    for (int i =0; i < arrTemp.length; i++){
        frGameOptions.append("hello" + arrTemp[i] + "-" txtBully);
    }

  • Can we place Analog in Read(AI-RE​AD) Vi inside the while loop for high sample rate like 22ks/s?

    I am using E-series Card for data acquisition.My requirement is to sample the channel, and check the 10 samples for certain condition.both at a time.What should be done can we place the AI-READ vi inside for or while loop for this purpose?

    Hello,
    Yes, you can include the AI Read.vi inside the while loop, you would just need to specify the number of scans to read for every iteration of the loop. Then, after AI Read.vi has read the data, you can do what ever kind of manipulation of the data you would like, before the next iteration of the loop. The one thing to watch out for is what ever manipulation of the data you do, be sure that it doesn't take to long whereas the buffer holding the data starts to back up. That can be checked by looking at the scan backlog output of the AI Read.vi, which will tell you how many scans have been acquired but haven't been read into your program.
    Hope this helps!
    Regards,
    Steven B.
    Applications Engineering, NI

  • I have a for loop inside of while loop.when i press stop for while loop, i also would like to stop for loop.how can i solve this problem?thanks

    i have a for loop inside of while loop.when i press stop for while loop, i also would like to stop for loop.how can i solve this problem?thanks

    Hi fais,
    Following through with what JB suggested. The steps involved in replacing the inner for loop with a while loop are outlined below.
    You can replace the inner for loop with a while by doing the following.
    1) Right-click of the for loop and select "Repalce" then navigate to the "while loop".
    2) Make sure the tunnels you where indexing on with the for loop are still indexing.
    3) Drop an "array size" node on your diagram. Wire the array that determines the number of iterations your for loop executes into this "array size".
    4) Wire the output of the array size into the new while loop.
    5) Set the condition terminal to "stop if true".
    6)Drop an "OR" gate inside the while loop and wire its output to the while loops condition terminal.
    7) C
    reate a local of the boolean "stop" button, and wire it into one of the inputs of your OR gate. This will allow you to stop the inner loop.
    8) Drop a "less than" node inside the inner while loop.
    9) Wire your iteration count into the bottom input of the "less than".
    10) Wire the count (see step 4 above) into the top input of the less than. This will stop the inner loop when ever the inner loop has processed the last element of your array.
    Provided I have not mixed up my tops and bottoms this should accomplish the replacement.
    I will let others explain how to takle this task using the "case solution".
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How do I break a for loop (inside) and a while loop (outside) at the same time by a control button

    I have a while loop (outside) and a for loop (inside) and a control button within the for loop.  I want to stop the program by click the botton without finishing the for loop.  How can I do that?
    Thank you in advance.

    HI Please find attached snapshot Regards, Santosh
    Message Edited by SanRac on 12-17-2009 05:12 AM
    Message Edited by SanRac on 12-17-2009 05:13 AM
    Attachments:
    Snap1.png ‏4 KB

  • For loop inside  a while loop, what order is that in big o??

    If say I have a for loop inside a while loop, then is that suppose to be in the order of O(n^2) right?? Is there any possibilities to change this into the order of O(n)??

    the other size and the temp size is abstact, which can be defined. This is actually for my union method, my teacher asks me to write this method using the order of O(n) which I think it is not possible. What do you guys think??
    Below is the code I have made:
    public Set<E> union(Set<E> other) {
              int count = 0;
              Iterator<E> iterator1 = other.iterator();
              while (iterator1.hasNext())
                   count++;
              Object[] temp = new Object [data.length+count];
              n = data.length+count;
              for (int i = 0; i<count; i++)
                   temp[i] = data;
              for (int j = count; j<temp.length; j++)
                   temp[j] = iterator1.next();
              data = temp;
              return null;
    but it still has same elements on it and I am thinking of a way on how to remove those same elements

  • I'm creating an array using a for loop, how do I get the values outside the loop while it is running? thanks

    I'm creating a set of values using a for loop and a shift register inside the loop. I want access to these values outside the loop as they are being created inside. When I connect a wire from the shift register to a display outside, it doesn't work. How do I do this? Thank you.
    Attachments:
    tamko_new.vi ‏29 KB

    I tried to create the local variable that was wired to numeric indicator inside the loop. If I try to connect this to the analog output outside the loop, the loop just starts blinking and nothing happens, am I doing something wrong? Thanks again.
    Attachments:
    tamko_new2.vi ‏29 KB

  • Open and close visa inside a while loop

    Hi,
    I need to read a position from a control unit device continuously or even by click a button, for this I have to put "visa configure serial port" and" "visa close" inside a while loop. Dose it make any problem?

    You shouldn't need the VISA Event nodes.  Get rid of those.
    Why are you using Concatinate String just to build up a constant.  Just create a single string constant.  It is a lot cleaner.
    Is the antenna constantly sending data to you or only when you request it?
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Is there a way to run a For Loop independen​tly within a While Loop in LabVIEW 2013?

    In my program I would like to run a For loop inside of a While loop, and have them run independently, at their own execution rates.  As a test, I wrote a simple VI with a While loop with 1 second timing, and into this I inserted a For loop with 3 second timing.  I created indicators for both iteration terminals.  Upon running the VI, I found the While loop waits for the For loop to run N times before the While loop executes again.  I also found that sometimes the first iteration of the For loop will end at 1 second rather than 3 seconds, and the STOP button to terminate execution of the While loop does not always work.
    Solved!
    Go to Solution.

    ksinks wrote:
    Thanks, how would you synchronize the loops?  I have gone through the Getting Started exercises and manual.
    Why would synchronization matter? Did you want them to run independantly at their own speed or not?
    Regardless, there's a synchronization pallette with functions for this, as Occurance.
    Other solutions include a common loop counter and a case structure executing every X'th iteration, or having the faster loop send a queue or event every X'th loop that controls the slower loop.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • SubVi with feedback nodes used more than once inside a While Loop

    All,
    I have a subvi that does a set of operations and uses 3 feedback nodes. I am using this subvi inside a While Loop a total of 4 times. I've noticed that all instances used share the same result at each corresponding feedback node but I would like to have an individual result from each of them. Is there an easy way to go around this problem? I have come up with ways to avoid this: a) create a different vi for each time the subvi was used. b) use global variables instead of feedback nodes. Is there any easier way to go around this issue?
    ExamplePlease note that both subvi's are the same) If on my first subvi I calculate a maximum value and get 1.29 (then goes to feedback node) on my second subvi i get 1.01 my feedback node at the second subvi still registers the maximum value to be 1.29. (and I want it to be 1.01!)
    Hope this is not too confusing, I've been scratching my head with this for a while, can't find the "easy" button. Thanks in advance.
    -Pop
    Im using 9.0.
    Solved!
    Go to Solution.

    Attaching the code would be helpful. Anyway, I am not sure how multiple feedback nodes are supposed to operate so I will defer that to others to answer. As far as being able to use distinct values or instances if you are using a subVI you could mark it as reentrant. That way each call to it will behave as it it were a copy of the VI and it will have its own memory space. This should include the feedback node. You may be ending up with a single subVI and in reality a single feedback node. If you need to pass data between calls than simply wire the data through. You could also use an Action Engine to store and retrieve values. An AE is a MUCH better solution than a global variable.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • State Diagram inside For Loop

    I created a fairly involved for-loop with a flat sequence inside of it.  The sequence had about four events that occured, and since it was kind of ugly, I thought I'd try the State Diagram Toolkit to replace the majority of the code.  When I selected state diagram from the pallete, I was outside my for-loop.  I drew up the various states/transitions, then realized that all this code needed to be inside the for-loop, but LV won't let me place state diagram-generated code inside the for-loop.  I select everything related to the state diagram, but when I drag into the for-loop, only the comments come inside.  I even tried generating a new for-loop and placing the state code inside.  No luck. Any thoughts?

    "Any thoughts?"
    Yes but not any that will help.
    1) Just modify your SD so that the exit loops back to the start while there are still things to do. Forget the outer For loop.
    2) THe observations you reported are correct. When I first discovered these limitiations I said "That sucks!". Since then I have learned a bit and have grown to love the SDE.
    The SDE is JUST (note: "just" is a four letter word around here ) a LV application that ofers a very limited GUI consisting of a picture control that then scripts (see LAVA Scripting Forum for info on scripting) your SD for you. SCripting LV code is no easy task. My experiments with scripting has shown that I have to keep a database of the contents of the LV diagram my code is developing to keep track of what is where. Well it turns out that the structure of a LV diagram is a lot like the structure of a FP in that you start with a "root" object either the FP or the BD. THe BD then has structures on it, like seq's loops etc with unlited nesting possible.
    Now the SD created by the SDE is really just a fancy while loop with an case structure and code to support the driving enum. In order for you to be able to edit the SD the SDE needs to know what is htere already so it can show the diagram. It "KNOWS" by looking at its internal DB (I believe is stored inside of VI along with the enum.ctl) of the SD. To keep the DB updated, the SDE must be used to manipulate the SD.
    Stop rambling and guessing and get to the point!
    Moving the SD is just not supported by the SDE so it can not be done. To do so would require the SDE be able to "look" at the diagram, and repeat all of its work in the new location in the diagram.
    BTW: Thank you for trying out and asking about the SDE. the more talking we do on this subject, the sooner the SDE will be updated.
    My SDE wishlist (partial)
    Add comments to diagram from SDE screen.
    Add data structures to SD (shift registers) from SDE screen.
    Add "un-do".
    Select multiple objects on SDE screen and move or allign.
    Select multiple objects on SDE screen and do "create sub-State-Diagram".
    Allow watching more than one SDE in execution highlighting at the same time.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Unxepected behaviour with clusters inside of while loop with shift register

    Colleagues,
    I just would like to post here small, but important bug (I guess this is the bug), which was found by coworker today morning. Just would like to share knowledge, and probably this will save some debugging time for you...
    So, the problem that you can get wrong content of the cluster in some cases. The cluster used inside of while loop with shift register (we using this construction for functional globals), and after bundle operation you can get data, which are not expected:
    See also attached code for details (LabVIEW 8.6.1, WinXP Prof SP3).
    best regards,
    Andrey.
    PS
    Bug report already sent to NI.
    Message Edited by Andrey Dmitriev on 10-16-2008 12:30 PM
    Attachments:
    BugwithClusters.png ‏15 KB
    BugwithClusters.zip ‏10 KB

    Thanks Andrey for brining this to our attention!
    The "Show Buffer Allocations" reveals that LV is not processing the code in the right order.
    Under ideal conditions, all of the data should be manipulated using the buffer "A". But as this demo shows the data is being processed in the wrong order.
    The previously posted workaround get around this by forcing the array operation to happen first, but this resluts in two additional buffers "C" and "D" and then copy this back into "B".
    Using an "Always Copy" is another workaround that uses a seperate buffer "F" to hold the data being moved from the first cluster to the second inside "E".
    I think you won a shinny new CAR* Andrey!
    Ben
    CAR = Corrective Action Report
    Message Edited by Ben on 10-16-2008 08:05 AM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Attachments:
    Cluster_Bug.PNG ‏57 KB

  • How to create for loop USING a while loop

    Hi, I would like make a for loop inside of a while loop because I want to control the i count of the loop, and overall, more control over the loop. From what I understand, labVIEW's for loop doesn't let me change where the i count starts. It always start at i=0, and what I want to do is be able to jump to specific loop iterations and then continue from there.
    Thank you.

    That is not the same as the earlier examples.
    If you want 10 counts and start at 0, then the stop terminal will stop after 10 times.  Just like you get when you wire 10 into the N terminal and don't have a conditional loop.
    If your start value is larger, let's say 9, then your loop will only run 1 time because i=0 on first iteration + 1+ 9 (start value).  0 + 1 +9 = 10.
    If your start value is larger than 10, then it will run 10 times again because on the intial iteration the result of your comparison is already greater than 10 and won't stop, and will never be equal on later iterations.
    So your example does not even give consistent results depending on the value you use as the start value.
    (Just to note, my earlier examples may not all be identical results as I didn't try to verify all the stop conditions nor the array that is output by the ramp function.  I could be off by one iteration here or there.  But they should be good enough to point out distinctive ways to accomplish what the OP asked for.)

Maybe you are looking for

  • Spool Error capture question

    Hi, I am trying to spool data from tables into flat files. I am using the following scripts to accomplish it 1. A cmd file (windows) that makes a call to a sql file 2. The SQL file which generates another query file at the run time, depending upon th

  • My devices are not being recognized by iTunes, but they are with iPhoto?  I can't sync my iPod or iPad.

    Has this happened to anyone else.  Any ideas on what I did, or need to do??? Thanks

  • Design view not showing links in template

    Newbie here, I have downloaded a template from the web, that i wish to use, but when i try and insert an article onto DW, from ezinearticle using the html code supplied and pasting into the code view, the result in the design view is that the links t

  • Change Fill Color of a Thermomete​r

    This post is a continuation from an idea in the Idea Exchange about being able to change the fill colors of a thermometer. I am only posting here so that my attachment can be viewed (the Idea Exchange eats attachments, and potentially does not allow

  • Approval Workflow Folder Inheritance

    In a previous thread, it was confirmed that the approval/workflow setting are not inherited by sub-folders.   However, a user can create folders, therefore leaving a big hole in the approval process.  Does SAP have any timeline on when they will be a