A simple for loop question
Hi
Lets say I have an array with boolean values in it:
my_array = [ false , false , false ]
My question is:
How do you make a function to check, if the value is all
false, than do this (not only one but all false than trigger a
function)
thank you
The 350Z,
> Lets say I have an array with boolean values in it:
> my_array = [ false , false , false ]
I'm with ya.
> My question is:
> How do you make a function to check, if the value is
> all false, than do this (not only one but all false than
> trigger a function)
Your subject line already states the answer. A for loop
would come in
handy. :) In your case, you're looking for all three values
to be false.
If even a mere one of them is true, the whole result doesn't
count. Let's
write a function that returns true if all three are false,
and returns false
if any are true.
function checkWholeArray(arr:Array):Boolean {
for (var n:Number = 0; n < arr.length; n++) {
if (arr[n] == true) {
return false;
return true;
To use this function, you could call it and supply your
array as the
parameter ...
checkWholeArray(my_array);
... and since that resolves to either true or false, you
could even use that
expression in an if statement.
if (checkWholeArray(my_array)) {
// do something
} else {
// do something else
The for loop simply steps through each element in the
passed-in array.
If the current element is true, then the desired outcome --
that all
elements are false -- is a loss, so the function returns
false and
immediately stops (the return statement always exits the
function at that
point). Otherwise, the for loop finishes, and the function
returns true.
David
stiller (at) quip (dot) net
Dev essays:
http://www.quip.net/blog/
"Luck is the residue of good design."
Similar Messages
-
Hi,
I have a cursor in my plsql and I am trying to get the record through a FOR loop. I know that for loop will take care of opening, fetching and closing the cursor implicitly.
Ex.
declare
cursor c1 is
select * from emp;
begin
for l_rec in c1 loop
end loop;
My question is i want to check whether the cursor in the for loop is returning any record or not using IF condition.
where and how i will find that?
Can anyone help how to do that.
Rds,
Nagwithout using boolean variables.Obvious question, WHY?
If you are so particular..
SQL> declare
2 cursor c1 is
3 select empno, ename, job
4 from emp
5 where empno = 7839123;
6 ex exception;
7 rec c1%rowtype;
8 begin
9 open c1;
10 fetch c1 into rec;
11 if c1%notfound then
12 raise ex;
13 end if;
14 loop
15 dbms_output.put_line(rec.empno||'-->'||rec.ename||'-->'||rec.job);
16 fetch c1 into rec;
17 exit when c1%notfound;
18 end loop;
19 exception
20 when ex then
21 dbms_output.put_line('cur not found');
22 end;
23 /
cur not found
PL/SQL procedure successfully completed. -
VERY IMPORTANT FOR LOOP QUESTION
public class ForTest2 {
public static void main(String args[]) {
int i=0, j = 0;
for (j=0; j < 10; j++) {
i++;
System.out.println("i is: " + i);
System.out.println("j is: " + j);
System.out.println("Final i is: " + i);
System.out.println("Final j is: " + j);
}j ends up being 10. Why? It should only be 9. This is as when j is 10 the for loop fails, so j++ shouldnt happen.First, please, please, please stop using all caps. It's extremely annoying.
Second, don't mark your question as urgent or important. It is 100
% guaranteed NOT to get you help any faster, and it might just delay you getting help because it's annoying.
As for your question, you're misunderstanding how the for loop works. j HAS to become 10 for it to end. The loop body executes as long as j < 10. If j didn't become 10, the loop body couldn't terminate, because j<10 would always be true.
The body is executed, the j++ is executed, then the j<10 is tested.
int j;
for (j = 0; j < 10; j++) {
// body
// is equivalent to
int j;
j = 0;
while (j < 10) {
// body
j++:
} -
Stacked sequence inside for loop question
Hi everyone,
I am new to LabVIEW and I just want to make a for loop with a stack sequence inside. I want it so that when the for loop executes for the n-th time, the stacked sequence is at the n-th frame (because each frame contains different tasks to be carried out). Is this possible? or is there an alternative equivalent method? Please help me out! Thanks!!Thank you Norbert for the words of advice.
Try to avoid Stacked Sequence Structures at all cost. They are a nightmare to deal with when maintaining the code and they do not offer simple scalability, especially if you need to deal with parallelism.
As Norbert suggested, State Machines is the way to go. Try to avoid naming covention such as 1...2...3...4...5.......9999. Give the name of each case based on what that case does. Create a TypeDef Control for the state selector (you'll thank me after having changed it for the 5th time ).
There are probably 100's of examples in this forum.
RayR -
What is wrong with this simple for loop?
long number = 12345678;
for(int i=1;i<=numberOfDigits;i++)
int i = number/(i);
System.out.println(i);
Basically, I want to take to assign int 1 = , int 2 = , int 3 = up until the number of digits.
I still have to manipulate it, so the code makes no sesne, but how would I do that?
So, i want to assign ints up until 8 but the manipulation I have also involves i up until the number of digits.
Yhank you.Fredddir_Java wrote:
I see that, but I just wanted to declare 8 ints (in this example, number of digits is 8) using a for loop, so I wanted to use the loop to assign these values one at a time. You know...but don't declare a variable with the same name as the loop variable. That just won't compile. Use an array as mentioned above.
How would you do that?If you are trying to find the digit at a certain point in your number, probably the easiest way is to translate the number to a Stirng and use String methods (if allowed) such as charAt(...). If not, then look at the mod operator "%" and at integer division.
Can anyone provide a basic loop for this task?Best not to ask for a code solution to homework here. We'll tolerate specific questions but not requests for code. -
Insert Procedure For LOOP question
Hi all,
I have made a Procedure which basically massages data and loads into into another table and makes a time record aswell. I am practising my good datawarehousing practise (So load table into real DW_table)
I am using an Explicit Cursor For Loop....
What i was wondering is if there is some type of SQL%rowcount I can do in order to check that the record where "INSERTED" into dw_client and dw_time; before i create a auit record in another table. I know this is normally done using triggers, but I am testing this for a Datawarehouse and not sure triggers are the best answer. But please correct me if im wrong:
I basically wanted to put another insert in there, if the inserts actually ran!RPuttagunta wrote:
Why can you not use a merge statement in your code instead of writing a whole procedure for it?
merge into mehmet_schema.dw_client a
using
mehmet_schema.client.....
If I understand it right, you are checking if there are any records that exists in 'client' and doesn't exist in 'dw_client' table, then, you are inserting. Is that correct?Yes that is correct. Also I am inserting into the dw_time table using the sqeuence values, so i didnt think merge statement would do this!
aslo i wanted to use this procedure to clean up some of the data, as you can see in my Cursor, again why i havent used a merge
Edited by: oraCraft on 09-Nov-2010 09:53 -
Hi here is a segment of my code:
public void vietaLoop(){
int loopParameter;
final int START_CONDITION=0;
final long END_CONDITION=no_Terms;
double initialTerm = Math.sqrt(2)/2;
double newTerm;
double previousTerm;
/* calculate the next PI term */
newTerm = Math.sqrt(2+previousTerm);
/* assign new term to previous */
previousTerm = newTerm;
for (loopParameter = START_CONDITION; loopParameter < END_CONDITION;
loopParameter++)
/* Prints the new PI approximation */
System.out.println(+ newTerm);
im having loads of trouble, above is how far I have got but I'm unable to 'call' the previous calculation to be included in the next calculation to calculate the new term of PI. as a result all my output is the same..... ie = 1.645.......
If anyone could point me in the right direct... its really getting to me. Thanks.Hi there,
Is this what you want?
import java.awt.*;
class vietaLoop
public static void main(String[] args)
int loopParameter;
int no_Terms=10;
int START_CONDITION=0;
int END_CONDITION=no_Terms;
double initialTerm=Math.sqrt(2)/2;
double newTerm;
double previousTerm;
previousTerm=initialTerm;
for (loopParameter=0; loopParameter<END_CONDITION;loopParameter++)
newTerm = Math.sqrt(2+previousTerm);
previousTerm = newTerm;
System.out.println(newTerm);
}If you use it as a function, set it as
public double vietaLoop(int noTerm)
Then you can change no of term for looping.
Regards
John -
Hi everybody,
I have a feeling this is so obvious that I'm missing it, so if anyone would give me some advice, I'd appreciate it.
I have a method with with three parameters that loops through them and progressively adds or subtracts them with a for loop, based on the order. The only way I can think of to do this, though, is with two for loops with almost identical code. I know there must be an easier way to do this, but I think I've been staring at it too long, can anyone give me a hand conceptually, please?
The method is:
private void create( int param1, int param2 ) {
int entries = 5;
double increment;
if( param1 > param2 ) {
increment = param1 - param2;
for( int i = 0; i < entries; i++ ) {
System.out.println( param1 - ( i * increment ) );
} else if( param2 > param1 ) {
increment = param2 - param1;
for( int i = 0; i < entries; i++ ) {
System.out.println( param1 + ( i * increment ) );
}Thanks,
Jezzica85
Edited by: jezzica85 on Mar 30, 2009 2:38 PMprivate void create( int param1, int param2 ) {
if( param1 > param2 ) {
create(param2, param1);
} else if( param2 > param1 ) {
int entries = 5;
double increment = param2 - param1;
for(int i = 0; i < entries; i++ ) {
System.out.println( param2 + (i * param1));
} //equal do nothing?
}or
private void create2( int param1, int param2 ) {
if (param1 != param2) {
int entries = 5;
int minParam = Math.min(param1, param2);
int maxParam = Math.max(param1, param2);
double increment = maxParam - minParam;
for( int i = 0; i < entries; i++ ) {
System.out.println( maxParam - (i * minParam));
} -
I like it, but I can't figure out how to use it for the following situation (printing contents of two arrays using one iterator):
old way:
System.out.println(menuTitle + "/n");
for (int e ; e < length.menuChoices ; e++)
System.out.print(menuChoices[e] + " - " + menuLabels[e]);
}new?
System.out.println(menuTitle + "/n");
for (String e : menuChoices)
System.out.print(e + " - " + menuLabels[????]);
}Is there a nice way to do this or should I just use the old for loop and hope my teacher doesn't think that I just don't know about the new loop? Thanks.Is there a nice way to do this or should I just use
the old for loop and hope my teacher doesn't think
that I just don't know about the new loop?No there isn't. In the new for-loop the loop counter has been abstracted away. You'll have to either use the old for-loop, or introduce a counter in the new.
Another way could be to change the design a little.
class MenueItem {
Type1 choice();
Type2 label();
for (String e : menuItems) { // all MenuItems
System.out.print(e.choise() + " - " + e.label());
} -
I am using this to create a data set that will be passed as an anolog output therefore it needs to have the correct array dimensions to go into the analog write vi.
I'm updating my request... I've figured out how to do this by copying an example that uses a simple FOR loop (as seen in the attached current version of my VI). My question now becomes this: Is there a way to save the Y values corresponding to those X values into two more arrays? That is, just for argument's sake, let's say I took the first 100 elements from the X array, and found them to be positive. Then I would like to take the first 100 elements of the Y array and put them into a 'Y Values for X > 0' array. ...And likewise with the negative X values, they should have a separate array of corresponding 'Y values for X < 0' array.
I can see that I should somehow save the indices of the positive X values from the large arrray wh
en I sort them out, and use those indices to pick out the elements from the main Y array with the same indices.
I just can't seem to set up the code necessary to do this. ...Can anyone help, please?
Attachments:
Poling_Data_Reader_5i.vi 79 KB
30BLEND.txt 3 KB -
Select statement in a for loop
Hi all,
Can a select stmt be used in the body of the for loop/ nested for loop ?
I tries using (even if its very simple for loop) it gives the following error
PL/SQL: ORA-00933: SQL command not properly ended...
code is
DECLARE
CURSOR C1 is select 'Monday' from dual
union all
select 'Tuesday' from dual
union all
select 'Wednesday' from dual
union all
select 'Thursday' from dual
union all
select 'Friday' from dual
union all
select 'Saturday' from dual
union all
select 'Sunday' from dual;
type rec_info is record
name varchar2(20),
FNAME varchar2(20),
LNAME varchar2(20)
type ty_info is table of rec_info;
info ty_info;
type rec_abc is record
day varchar2(3000)
type ty_abc is table of rec_abc;
abc ty_abc;
Cursor C2 is
select t.name, u.first_name, u.last_name
from territories t, users u, territories_users tu
where t.ID = tu.TERRITORY_ID
and tu.USER_ID = u.ID ;
BEGIN
OPEN C1;
Loop
FETCH C1 into abc;
EXIT when C1%notfound;
DBMS_OUTPUT.PUT_LINE(abc);
END LOOP;
CLOSE C1;
OPEN C2;
FETCH C2 BULK COLLECT into info;
CLOSE C2;
for i in info.first .. info.last
LOOP
for j in abc.first .. abc.last
LOOP
select --info(i).name, info(i).FNAME, info(i),LNAME,'AM' "AM/PM",
to_char(c.name)||' '||ct.PRIMARY_ADDRESS_CITY||','||ct.PRIMARY_ADDRESS_STATE||','||ct.PRIMARY_ADDRESS_COUNTRY
from
territories t, territories_users tu,
users u, calls_users cu, calls c,
calls_contacts cc, contacts ct
where
tu.TERRITORY_ID = t.id
and t.name = info(i).name
and u.first_name = info(i).FNAME
and u.last_name = info(i).LNAME
and (c.date_start between trim(next_day(sysdate,abc(j).day)) and trim(next_day(sysdate,abc(j).day)))
and tu.USER_ID = u.id
and cu.USER_ID = u.id
and cu.CALL_ID = c.id
and to_char(c.time_start,'hh24') < '12'
and cc.CALL_ID = c.ID
and cc.CONTACT_ID = ct.id
and rownum < 2
END LOOP;
END LOOP;
END;"Can a select stmt be used in the body of the for loop/ nested for loop "
Yes.... but with an INTO part.....
select c1 , c2 , c3 into var1 , var2 , var3 from table1
Sim -
Hi,
Anyone who can tell me how to create a Fibonacci range from the first 15 characters, using a simple for loop?
TIA!Well, the good news is that your sequence generating code works:public class FibTest {
public static void main(String[] args) {
int fib1 = 0;
int fib2 = 1;
int xPos = 0;
for(int i = 1; i <= 15; i++) {
int temp = fib1;
fib1 += fib2;
fib2 = temp;
System.out.println(i + ": " + fib1);
}. As for your output, how messed up is it? Are you not getting enough spacing between terms? You should be able to play with your drawString method and make it look better. Is it a requirement to make this an applet?
Good Luck
Lee -
For Loop and Void Method Questions
Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted.
Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)?
Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now.
for (int index = 0; index < howNum; index++) // process each number in the array
enterYourNumbers = JOptionPane.showInputDialog
("Enter a number between 1 and 100");
numArray = new double[howNum];
try
numArray[index] = Double.parseDouble(enterYourNumbers);
catch (NumberFormatException e)
enterYourNumbers = JOptionPane.showInputDialog
("Enter a number between 1 and 100");
DecimalFormat fmt = new DecimalFormat ("###,###.00");
JOptionPane.showMessageDialog(null, enterYourNumbers + " " + "squared is " + fmt.format(calcSquare(numArray[index]))
+ "\n" + enterYourNumbers + " " + "cubed is " + fmt.format(calcCube(numArray[index])));
wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
while (wantToContinue.equalsIgnoreCase("y"));
import javax.swing.*;
import java.text.DecimalFormat;
public class Array
public static void main(String[] args)
int howNum = 0;
int whichNum = 0;
double[] numArray;
boolean invalidInput = true;
String howManyNumbers, enterYourNumbers, wantToContinue;
do // repeat program while "y"
do // repeat if invalid input
howManyNumbers = JOptionPane.showInputDialog
("How many numbers do you want to enter");
try
howNum = Integer.parseInt(howManyNumbers);
invalidInput = false;
catch (NumberFormatException e )
howManyNumbers = JOptionPane.showInputDialog
("How many numbers do you want to enter");
while (invalidInput);
for (int index = 0; index < howNum; index++) // process each number in the array
enterYourNumbers = JOptionPane.showInputDialog
("Enter a number between 1 and 100");
numArray = new double[howNum];
try
numArray[index] = Double.parseDouble(enterYourNumbers);
catch (NumberFormatException e)
enterYourNumbers = JOptionPane.showInputDialog
("Enter a number between 1 and 100");
DecimalFormat fmt = new DecimalFormat ("###,###.00");
JOptionPane.showMessageDialog(null, enterYourNumbers + " " + "squared is " + fmt.format(calcSquare(numArray[index]))
+ "\n" + enterYourNumbers + " " + "cubed is " + fmt.format(calcCube(numArray[index])));
wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
while (wantToContinue.equalsIgnoreCase("y"));
public static double calcSquare(double yourNumberSquared)
return yourNumberSquared * yourNumberSquared;
public static double calcCube(double yourNumberCubed)
return yourNumberCubed * yourNumberCubed * yourNumberCubed;
public static void calcAverage(double yourNumberAverage)
}DeafBox wrote:
Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted. Use a while loop instead.
Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)? Why would you want to use 2 methods. Use the loop to sum the numbers. Then after the loop a single line of code calculates the average.
Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now. If I understand you correctly, use 2 loops. One gathers user inputs and stores them in an array/List. The second loop iterates over the array/List and does calculations. -
Simple Router Question (except not simple for me)
(Couldn't find another place for this question so I put it here.)
I have a router between my broadband modem and my Macs on the blink. I want to get a new one. I'm not asking for product recommendations as much as terminology clarification.
Again, I need a box that accepts my ethernet cable coming out of my broadband modem. I don't need wireless. It's simply going to allow me to offer ethernet cables out to Airport Express, iMac, etcetera.
What am I precisely looking for?
An ethernet router? Splitter? Does it need to have some sort of high bandwidth? The thing is I see these produces vaguely named and prices all over the place. A simple ethernet 'hub' strikes me as something very cheap ($20-30).
Any help truly appreciated.Unless your broadband modem is "Also" a router, you need a router.
The Airport Express is a router, but it takes the ethernet cable and provides routing services for WiFi devices. It will not provide additional ethernet services for other devices.
You can NOT use an ethernet switch nor an ethernet hub.
While you can get ethernet only routers, the chances are that you will pay a premium over just getting a WiFi base station.
A WiFi base station is mostly a commodity items so they are often very inexpensive.
If you really do not need the WiFi services, many WiFi base stations allow you to turn off the WiFi.
Also note. If you are going to use the Airport Express to provide your WiFi, then you should configure it so it is in "Bridge" mode, otherwise you will have multiple isolated subnets where the devices on WiFi will not be able to properly see the devices on your ethernet. Putting the Airport Express in "Bridge" mode makes the WiFi network part of the same subnet that the ethernet devcies are on. -
How do I select a square brush for the brush tool in CS6? Sorry if this is a simple question, but nothing has ever been simple for me in Photoshop.
I don't believe there is a square brush among the sets that ship with Photoshop, but there are plenty to download, and it is super easy to make one.
Just drag with the rectangular Marquee tool, fill with black on a new layer, and go Edit > Define brush preset
Browsing Photoshop Brushes on DeviantArt
Maybe you are looking for
-
Hello expert, I use VL10E, and I cannot ask for more than 30 days in deliv creation date. Do you know how to change it ? Thanks
-
I recently changed my apple ID but my previous apple ID is associated with my icloud account. I'm setting up my new iphone 6 and cannot complete the set up until I can sync my icloud account. Does anyone know how to change the icloud id?
-
Hi, I have de mars v.6.0.6. The problem is: The FWSM option is not available in Add Module (Admin>System Setup>Sec& monitor device>add), only are available IOS, ASAs, PIX. The version FWSM is 4.1 Appreciate your comments, jorge
-
Hi folks, Some body could helpme? I need to review all Cubes that not have "Aggregate Indexes". Question: Do you know wich TABLE contain this information?, to know faster all my cubes without aggregate indexing?. Tanks so much
-
InDesign CC 2014 crashes when creating alternative layouts
InDesign CC 2014 crashes when creating alternative layouts. I successfully created alternative layouts in 3 documents, now I cannot create any at all, it just crashes the program.