Exiting the loop.....
I am writing an app that reads an arbitrary # of int's ranging from 0 to 50 inclusive and counts how many times each number is entered. After the input has been processed - prints all the values and number of occurances for each number.
Here is what I have so far. I am having trouble exiting the do..while loop without getting errors. I don't want the user to have to reply "y" or "n" after each entry. Any ideas?????
import cs1.Keyboard;
public class IntegerCount
public static void main (String[] args)
final int MIN = 0;
final int MAX = 50;
int[] numbers = new int[MAX];
int[] numbers2 = new int[MAX];
int index = 0;
int num = 0;
char stop;
System.out.println ("Enter a number between 0 and 50: ");
System.out.println ("To summarize your values enter the = ");
do
stop = Keyboard.readChar();
num = Keyboard.readInt();
numbers[index] = num;
index++;
while ((num>=0 && num<=50) && stop != '=');
index = 0;
for (int i = index; index < numbers.length; index++)
if (numbers[index] != 0)
System.out.println (index + " " + numbers[index]); //test numbers[]
numbers2[numbers[index]] = numbers2[numbers[index]] + 1;
index = 0;
for (int i = index; index < numbers2.length; index++)
if (numbers2[index] != 0)
System.out.println (index + " " + numbers2[index]);
It looks like the limitation requiring the entry of a y or an
n is contained in the Keyboard class. If you will
substitute this code for the do loop, it will take care of
the problem:
String s = "";
int num = 0;
int total = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
try {
s = br.readLine().trim();
catch (IOException ioe) {
ioe.printStackTrace();
if (s.charAt(0) != '=') {
try {
num = Integer.parseInt(s);
catch(NumberFormatException nfe) {
System.out.println("Invalid number. Zero substituted.");
num = 0;
total += num;
while(s.charAt(0) != '=' && (num >= 0 && num <= 50));Mark
Similar Messages
-
Exit the loop of screen in Module pool
Hi,
My requirement is : in my screen i have Table control. When i select any line (the value of select coloum will be 'X' ) and click on one button (Detail is button in my screen) the loop - endloop should exit at that line.
for example : if i select 5th line of table control then the data of 5th line will be in the header of internal table and the value of select coloum will be 'X'. i want to exit at that point itself. i dont want internal table to loop in PAI.
my code is :
PROCESS AFTER INPUT.
LOOP AT IT_ZINVH.
MODULE EXIT_LOOP.
ENDLOOP.
MODULE EXIT_LOOP INPUT.
IF IT_ZINVH-SEL = 'X'.
EXIT .
ENDIF.
ENDMODULE. but here if i use EXIT it is only comming out of IF-ENDIF contidion.
Thanks & RegardsHi,
Try this way.
<li>Code PAI like below
PROCESS AFTER INPUT.
LOOP AT it_zinvh.
MODULE read_table_control.
ENDLOOP.
MODULE user_command_1001.
<li>Module read_table_Control should be like below.
*& Module READ_TABLE_CONTROL INPUT
MODULE read_table_control INPUT.
MODIFY it_nfal INDEX tchkbox-current_line.
"The above Modify statement modifies the table for the column SEL = 'X'.
ENDMODULE. " READ_TABLE_CONTROL INPUT
<li>Write action when you click on DETAIL button. Lets say DETAIL is the function code for Details screen button.
*& Module USER_COMMAND_1001 INPUT
MODULE user_command_1001 INPUT.
CLEAR ok_code.
ok_code = sy-ucomm.
CASE ok_code.
WHEN 'DETAIL'.
LEAVE TO LIST-PROCESSING AND RETURN TO SCREEN 0.
LOOP AT it_zinhv WHERE sel = 'X'.
WRITE:it_zinhv.
EXIT.
ENDLOOP.
ENDCASE.
ENDMODULE. " USER_COMMAND_1001 INPUT
Thanks
Venkat.O -
How 2 exit the Loop..?
Hello all,
Can any tell me how to get out of this Loop in case of changing the range registered or stored in the db on update in a reange smaller than rang_to i got the message and the raise poped up i need the following logic 2 covers all possible ranges so can any boady help me, sorry 4 the cap locks and sorry that i have to leave 2 4 a vacation..)) reallly..!
Well the following code describes my case is as follows:
=========================================
--------------------------------RANGE VALIDATION----------------------
DECLARE
V_MESSAGE NUMBER(2);
V_RANGE_TO DATE ;
V_RANGE_FROM DATE;
--V_TANK_COUNT NUMBER;
CURSOR RANGE_CURSOR IS
SELECT TANK_CODE,RANGE_TO,RANGE_FROM
FROM PLN_TANK_DEPTH_RANGE
WHERE TANK_CODE= :PLN_TANK_DEPTH_RANGE.TANK_CODE;
BEGIN
FOR I IN RANGE_CURSOR LOOP
--- INSIDE THE RANGE
IF ((:PLN_TANK_DEPTH_RANGE.RANGE_FROM >= I.RANGE_FROM ) AND(:PLN_TANK_DEPTH_RANGE.RANGE_TO <= I.RANGE_TO ) ) OR ((:PLN_TANK_DEPTH_RANGE.RANGE_FROM > I.RANGE_FROM ) AND (:PLN_TANK_DEPTH_RANGE.RANGE_FROM <= I.RANGE_TO )) THEN
V_MESSAGE := FUNC_MSG(1,'not within the range);
RAISE FORM_TRIGGER_FAILURE;
ELSIF (:PLN_TANK_DEPTH_RANGE.RANGE_FROM > I.RANGE_FROM ) AND (:PLN_TANK_DEPTH_RANGE.RANGE_FROM < I.RANGE_TO ) AND (:PLN_TANK_DEPTH_RANGE.RANGE_TO > I.RANGE_TO ) THEN
V_MESSAGE := FUNC_MSG(1,'not within the range);
RAISE FORM_TRIGGER_FAILURE;
ELSIF (:PLN_TANK_DEPTH_RANGE.RANGE_FROM < I.RANGE_FROM ) AND (:PLN_TANK_DEPTH_RANGE.RANGE_TO > I.RANGE_FROM ) THEN
V_MESSAGE := FUNC_MSG(1,'not within the range); RAISE FORM_TRIGGER_FAILURE;
ELSIF (:PLN_TANK_DEPTH_RANGE.RANGE_FROM < I.RANGE_FROM ) AND (:PLN_TANK_DEPTH_RANGE.RANGE_TO > I.RANGE_TO ) THEN
V_MESSAGE := FUNC_MSG(1,'not within the range); RAISE FORM_TRIGGER_FAILURE;
END IF;
END LOOP;
END;
===========================================================
Any suggestions will be welcomed,
Regards,
Abdetu..
===========================================================Exit;
-
Prematurely exit enumeration loop
i am enumerating thru a loop
upon a certain condition, i want to exit the loop, while keeping the object of the current enumeration in tact.
Foo foo = null;
Enumeration = fooVector.elements();
while(Enumeration.hasMoreElements())
foo = (Foo) enumeration.nextElement(); // get a foo
if (some condition is met)
// exit loop, but keep object foo in tact
// that is, don't do foo = nextElement()
}I suppose i could do the following, but is there anything more graceful?
Foo foo = null;
Foo foundFoo = null;
boolean found = false;
Enumeration = fooVector.elements();
while(Enumeration.hasMoreElements())
foo = (Foo) enumeration.nextElement(); // get a foo
if ((some condition is met) && (! found))
foundFoo = new Foo(foo);
found = true;
// use foundFooFoo foo = null;
Enumeration = fooVector.elements();
while(Enumeration.hasMoreElements())
foo = (Foo) enumeration.nextElement(); // get a
a foo
if (some condition is met)
{break; //This is what you want to do
// exit loop, but keep object foo in tact
// that is, don't do foo = nextElement()
/Kaj -
Set a container element inside class to exit a loop
Hi,
I want to set a container element inside a class to exit a loop.
The element is marked as import/export parameter and the binding from the task to the container exists as well.
The loop has a condition &finish& = X but I cannot exit the loop. Looks like the value gets never updated in the container.
When i am using a container operation to set the element its working but i want to do this out of my method in the class.
Is it not possible to change a container element inside a loop without using a container operation?
Thanks,
ChristophHi,
Using the container operation is a good method to solve the problem. But if you intend to do that in the method coding itself then you will have to have it as the export parameter of the method. You can view all the import and export parameters of a method by going to the Business Object Builder (SWO1) and then choose the method and click on the "Parameters" Button. Once you are done with the interface of the method use that method in the workflow builder as a task and in the binding there are two rows. One for the import that occurs just below the container elements and the export parameters appear below the import in a separate window. Make sure you have the binding set there too as this is where you can transfer the container elements back to the workflow container from the task container and it should work. Maybe you are missing that in the binding.
Hope it helps,
Sudhi -
if in a loop iam checkin a condition n if the condition satisfies then which is the best way to exit the loop.
Hi Sushant,
Use EXIT in the LOOP after the condition .If u use STOP it will exit from the Program.
Try this example creating a Program by uncommending EXIT and STOP.
DATA: t_mara TYPE STANDARD TABLE OF mara.
DATA: w_mara TYPE mara,
sum TYPE i.
SELECT matnr mtart FROM mara INTO CORRESPONDING FIELDS OF TABLE t_mara
WHERE mtart EQ 'KMAT' OR mtart EQ 'FERT' OR mtart EQ 'LGUT'.
sum = 0.
IF sy-subrc EQ 0.
SORT t_mara BY mtart.
LOOP AT t_mara INTO w_mara.
IF w_mara-mtart EQ 'LGUT'.
sum = sum + 1.
EXIT.
*STOP.
ENDIF.
ENDLOOP.
ENDIF.
WRITE : sum.
Reward Points if useful.
Regards
Avi... -
The attached file is work inprogress, with some dummy data sp that I can test it out without having to connect to equipment.
The second tab is the one that I am having the problem with. the output array from the replace element appears to be starting at the index position of 1 rather than 0 but that is ok it is still show that the new data is placed in incrementing element locations. However the main array that I am trying to build that is suppose to take each new calculation and place it in the next index(row) does not ap
pear to be working or at least I am not getting any indication on the inidcator.
Basically what I am attempting to do is is gather some pulses from adevice for a minute, place the results for a calculation, so that it displays then do the same again the next minute, but put these result in the next row and so on until the specifiied time has expired and the loop exits. I need to have all results displayed and keep building the array(display until, the end of the test)Eventually I will have to include a min max section that displays the min and max values calculated, but that should be easy with the min max function.Actually I thought this should have been easy but, I gues I can not see the forest through the trees. Can any one help to slear this up for me.
Attachments:
regulation_tester_7_loops.vi 244 KBI didn't really have time to dig in and understand your program in depth,
but I have a few tips for you that might things a bit easier:
- You use local variables excessively which really complicates things. Try
not to use them and it will make your life easier.
- If you flowchart the design (very similar to a dataflow diagram, keep in
mind!) you want to gather data, calculate a value from that data, store the
calculation in an array, and loop while the time is in a certain range. So
theres really not much need for a sequence as long as you get rid of the
local variables (sequences also complicate things)
- You loop again if timepassed+1 is still less than some constant. Rather
than messing with locals it seems so much easier to use a shiftregister (if
absolutely necessary) or in this case base it upon the number of iterations
of the loop. In this case it looks like "time passed" is the same thing as
the number of loop iterations, but I didn't check closely. There's an i
terminal in your whileloop to read for the number of iterations.
- After having simplified your design by eliminating unnecessary sequence
and local variables, you should be able to draw out the labview diagram.
Don't try to use the "insert into array" vis since theres no need. Each
iteration of your loop calculates a number which goes into the next position
of the array right? Pass your result outside the loop, and enable indexing
on the terminal so Labview automatically generates the array for you. If
your calculation is a function of previous data, then use a shift register
to keep previous values around.
I wish you luck. Post again if you have any questions. Without a more
detailed understanding of your task at hand it's kind of hard to post actual
code suggestions for you.
-joey
"nelsons" wrote in message
news:[email protected]...
> how do I create a 1d array that takes a single calculation and insert
> the result into the first row and then the next calculation the next
> time the loop passes that point and puts the results in thsecond row
> and so on until the loop is exited.
>
> The attached file is work inprogress, with some dummy data sp that I
> can test it out without having to connect to equipment.
> The second tab is the one that I am having the problem with. the
> output array from the replace element appears to be starting at the
> index position of 1 rather than 0 but that is ok it is still show that
> the new data is placed in incrementing element locations. However the
> main array that I am trying to build that is suppose to take each new
> calculation and place it in the next index(row) does not appear to be
> working or at least I am not getting any indication on the inidcator.
>
> Basically what I am attempting to do is is gather some pulses from
> adevice for a minute, place the results for a calculation, so that it
> displays then do the same again the next minute, but put these result
> in the next row and so on until the specifiied time has expired and
> the loop exits. I need to have all results displayed and keep building
> the array(display until, the end of the test)Eventually I will have to
> include a min max section that displays the min and max values
> calculated, but that should be easy with the min max function.Actually
> I thought this should have been easy but, I gues I can not see the
> forest through the trees. Can any one help to slear this up for me. -
Exit a loop when the condition in if succeed
Hello everbody:
LOOP ....
IF ...
"If the sentence here succeed I want to exit of the loop.
ENDIF.
ENDLOOP.
Some ideas pleaseHi
Try this
Loop ....
if 1=1
begin
goto ExitLoop
end
ExitLoop:
Regards -
How to EXIT the while loop in Event response section?
I'm writing a program to grab image using a NI card. The application uses the Event structure. When the GRAB button was pressed, it snaps image continually by putting the SNAP function in a while loop. Is there some way to exit the while loop?(Note :The while loop was put in the GRAB IMAGE event response section.)
edit this event-case AND uncheck "lock front panel until the event case for this event completes".
BTW, your thanks should go to Ankita, <a href='http://forums.ni.com/ni/board/message?board.id=170&message.id=151282'>here</a>
cheers!
Message Edited by Dynamik on 11-13-2005 01:26 AM
Message Edited by Dynamik on 11-13-2005 01:38 AM
When they give imbeciles handicap-parking, I won't have so far to walk!
Attachments:
untitled.GIF 20 KB -
loop at itab.
if <CONDITION>
<EXIT LOOP>
endif
endloop.
this ths condition , pz tel how to exit from loopHi
Loop
statements
EXIT
Endloop.
Will comes out of the loop.
Regards,
Sreeram Kumar.Madisetty -
Why doesn't the loop exit?
I have my program prompting the user for a code in letters.
System.out.print("Enter Code: ");
code = TextIO.getlnString();
code = code.toUpperCase();
//uppercase so I don't have to code for small letters tooFollowing this I'm using a while loop to check if the code contains numbers or anything other than letters.
hecknum = (int) code.charAt(p);
while ((checknum >= 91) || (checknum <= 64)) {
System.out.println();
System.out.println("Codes may only contains letters from A to Z.\n");
System.out.print("Enter Code: ");
code = TextIO.getlnString();
code = code.toUpperCase();
}This only works partially however. If I enter letters the first time through, everything will work fine.
If I enter numbers or some other symbols, I get the error and am re-prompted for the code. Thing is, if I enter only letters the second time around, I get the error message again, as if I had entered numbers or something.
I have no clue why... from what I see it should work...
Can anyone help me figure this out?inside the while loop you never change the value of checknum, so if the codition is tru when you enter the loop, it stays true
looks like you need to change p and recalculate checknum -
HOW DO I KEEP AN ARRAYLIST IN RANDOM ORDER AFTER EXITING THE SUB ROUTINE CONTAINING IT
PLEASE HELP!I am trying to go from VB4 which I loved to VB2010 which I find somewhat more challenging. I’ve searched the web for help and have adapted the following to my project. This code does
rotate randomly through every card in the deck and displays unique cards until all have been drawn. BUT I want to draw one card
only from the first “hat” of Boy’s names; then draw the second card from the second “hat” of Girl’s names and repeat this process until all cards in both decks have been drawn. How do I get the TextBox (OR any
MsgBox) to display JUST ONE unique random card at a time so I can exit that deck and go to the next deck?
On my form, I have two TextBoxes (to display the names (as drawn), two buttons (to re-load each deck once exhausted) and one command (&End)control (to end the process). I created two ArraysLists
(to hold the Boys names and Girls names separately) and two ArrayLists to hold the cards for the random decks when created in code.
I can
NOT get this code to draw random UNIQUE names once I exit the deck. I have tried to ReDim the deck; randomly pull a card from the second (temp) deck, etc
NOTHING seems to work.
WHY does my deck lose randomness once I exit it?
How can I fix it? I don’t understand this. Below is the code for the "hat" with the 10 girl's names.
Also, when I don't loop through all the cards, I usually get "An Out of Index exception was not handled" error. Hope someone can help me with this problem. It seems like this should
be easy BUT I'm baffled. Thank you for any help.
Imports System.Collections.Generic
Public Class Form1
Dim Count As Integer
Dim Rcard As New ArrayList
Dim Dcard As New ArrayList
Dim NewRDeck As New ArrayList
Dim NewDDeck As New ArrayList
Dim temp_Rnum As Integer
Dim temp_Dnum As Integer
Dim MyRand As New Random()
Public Sub Rcards_Click(sender As Object, e As System.EventArgs) Handles Rcards.Click
While Rcard.Count > 0
Dim temp_Rnum As Integer = Int(MyRand.Next(Rcard.Count))
NewRDeck(temp_Rnum) = Rcard(temp_Rnum)
Rem Check that the ArrayLists work correctly and display properly
MsgBox(Rcard(temp_Rnum), , "New random card selected is: ")
Console.WriteLine(Rcard(temp_Rnum))
Rcard.Text = (Rcard(temp_Rnum))
REM Now remove the Rcard with the random number generated so it can't be drawn again
Rcard.RemoveAt(temp_Rnum)
End While
REM When all 10 cards have been picked, alert player to re-load deck if desired.
MsgBox("No new cards left in deck; please Re-Load the cards. Thank you.")
EndSub
End ClassHi Acamar,
Thank you for such a fast response. Sorry if my text wasn't clear. I'm really struggling with creating unique random elements in Collections in VB2010 and feel I understand ArrayLists better than some of the other Collection types.The code works perfectly
and generates unique random cards until the original deck is exhausted. Then it prompts the user to re-load the original deck so it can be reused if needed. But I need to draw one card only and exit the deck. Then when I click on the TextBox again, I want
that deck to be in the same random order - just minus any cards I have already drawn and thrown away. Thanks again for your help.
Here's the rest of the code for just the girl's "hats" of names, if it helps:
Private Sub btnShuffleRCards_Click(sender
As System.Object, e
As System.EventArgs)
Handles btnShuffleRCards.Click
Dim j As
Integer
For j = 1 To 10
NewRDeck.Add(j)
Next j
Randomize()
REM Create original Deck with names for the girls.
Rcard.Add("1 HELEN”)
Rcard.Add("2 OLIVIA")
Rcard.Add("3 <st1:city w:st="on"><st1:place w:st="on">ALICE</st1:place></st1:city>")
Rcard.Add("4 VALERIE")
Rcard.Add("5 DONNA")
Rcard.Add("6 ZELDA")
Rcard.Add("7 MARGARIE")
Rcard.Add("8 <st1:city w:st="on"><st1:place w:st="on">NANCY</st1:place></st1:city>")
Rcard.Add("9 WANDA")
Rcard.Add("10 IRENE")
End Sub -
Hi every body
i have a procedure that execute a loop.What i want that to allow user to exit from loop before it finished(by using keyboard), i do that by pressing ctrl+alt+del which end the program it self.One could try putting the call to the procedure in a loop on the front end. Then check within the loop (in the front end ) whether the user has pressed a pre-defined button. If pressed, one could disconnect the connection or take some similar action that would stop processing the call to the stored procedure.
May be something like this is workable ... ?
Narayan.
null -
I'm a beginner. I'm trying to get this output
Initial number of stars:
7
Here's my program. What's wrong with it? Please help
import java.io.*;
class starWedge
public static void main (String[] args ) throws IOException
int numStars; // the number of stars
int row ; // current row number
int star; // the number of stars in this row so far
BufferedReader userin = new BufferedReader (new InputStreamReader(System.in));
String inputData;
// collect input data from user
System.out.println( "Initial number of stars:" );
inputData = userin.readLine();
numStars = Integer.parseInt( inputData );
row = 1;
while ( row <= numStars )
star = 1;
star = numStars - star;
System.out.print("*");
star = star + 1;
System.out.println(); // end each line
row = row + 1;Okay the one thing that I see immediately is that your while loop never actully exits. Not once. Why? Well simple your exit condition is the row <= numStars, yet nither numStars nor row actually change their values within the loop. In short row always equals 1 and thus never is equal to greater than numStars and the while loop does not terminate.
Second thing is that your star drawing logic is not correct. Meaning you have not told to draw the specific number of stars in one given line. For starters the System.out.println() command should be in the loop not outside it. For your purposes a for-loop nested within a while-loop is much better.
If you think you know what's wrong your program than read no further and go try it on your own. But if you still have no clue below is my modification of your code that actually produces the pattern you want, it might provide you with more hints.
import java.io.*;
class starWedge{
public static void main (String[] args ) throws IOException{
int numStars; // the number of stars
int row ; // current row number
int star; // the number of stars in this row so far
BufferedReader userin = new BufferedReader (new InputStreamReader(System.in));
String inputData;
// collect input data from user
System.out.println( "Initial number of stars:" );
inputData = userin.readLine();
numStars = Integer.parseInt( inputData );
row = 1;
while (numStars > 0){
for(star = 1; star<=numStars; star++){
System.out.print("*");
numStars = numStars - 1;
System.out.println(); // end each line
} -
Can Video widgets start and stop when entering and exiting the browser viewport?
I like to use multiple autoplaying/looping video clips on a single page but I need to figure out how to make the videos start only when they enter the viewport on a browser and stop after they exit the viewport. Does anyone know a way to do this?
I do not know if this can have an affect on it but the videos are being downloaded through multiple computers to a private server and being accessed through the mac. Please let me know what you think.
Maybe you are looking for
-
Application Server file into EXCEL SHEET
Hi , i want down load the Application Server FILE into EXCEL SHEET directly.. how to do this one. regards, venu.
-
Field catalog in two languages.
Hi friends, first of all, a very happy belated friendship day for all of u. I have a problem with me that I have to print the column headings in two languages i.e. our logon language and another language in brackets. Even in selection screen also I s
-
I didn't mess with this too much with my 3G because of limited space, but I've ripped a couple DVDs/Standard Definition using DVD Decrypter and encoded with HandBreak. I wish I could rip HD content. Are there any high quality HD video samples out the
-
While trying to play a game on facebook called "FrontierVille" I always get "adobe flash plugin crashed". I have uninstalled and re-installed the adobe flash player but to no avail. All the other games like "Farmville" work fine. Can anyone help m
-
Error creating unique tmp file
I get this prompt when trying to view video off yahoo or cnn. Does anyone know how to resolve this? Thanks, Mike