Menu
  • HOME
  • TAGS

Infinite while loop issues

c#,multithreading,while-loop

Another option is using ref to achieve what you want. Essentially, it allows you to pass a reference to your bool instead of the actual value at the time of evaluation. This allows changes to the value to affect the method it was passed to, even if it is a...

PHP While loop Notice: Undefined offset

php,while-loop

You should use foreach for iterating through arrays: foreach($data as $key => $value) {} Your warning with while is that you do check if this array position exists right. Use this instead: while(isset($data[$i])){} ...

Why this for loop doesn't do the same that the while loop?

c++,for-loop,while-loop

In your For Loop remove (change = false) from inside the for() statement. Let that for statement be for(std::size_t beg = 1, end = vec.size() - 1; (beg < end) && (change);) { // Write here change= false; ...... } It would work. Explanation: In your while loop code, your...

Why am I getting a debug assertion failed error on running the code

c,loops,debugging,while-loop

Replace while (j!=' ') by while (pass[j] != 0) You want to loop as long as pass[j] is different from zero. Remember, strings are terminated by a zero....

C code error: expected ';' before '{' token [closed]

c,while-loop

While(C[i] != '\0') should be while(C[i] != '\0') /* Note the lower-case 'w' */ Remember that the C programming language is case sensitive....

Displaying loop in JOptionPane

java,while-loop,joptionpane

I believe that you wish to print out all numbers from x that are less than or equal to f in a single DialogBox and not every time the loop iterates. import javax.swing.JOptionPane; public class Pr27 { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"); JOptionPane.showMessageDialog(null, "1 2 3 4...

How are the results for count different in all these three cases?

python,for-loop,while-loop,break

For Code 1, you're continuing to add on to the count. So during the first iteration, the count becomes 12 (the length of "hello, world" is 12), and then during the second iteration, you never reset the count to 0 so count is continuously added on until it reaches 24,...

(JS) Why is my While Loop not working!? Perhaps I don't understand the basic concept

javascript,while-loop

Am I right here: n is a variable, with value 4. while n = 4, print "Hey" in console. while(n) doesn't check to see if n is 4, it checks to see if n is truthy*. Both 4 and 5 are truthy values. To check if it's 4, use...

Incorrect output from while loop

c,while-loop

You call the enterNumber() function 5 times so 5 accepted values are taken : enterNumber(32,127); Please enter an integer between 32 and 127: 56 1st accepted number int min=enterNumber(32,127); Please enter an integer between 32 and 127: 56 // 2nd one 2nd accepted number enterNumber(min,127); Please enter an integer between...

Combine Grep and Regex?

ruby,regex,input,while-loop,stdout

You can try looping over the result of the grep like so: File.open("braslist.txt", "r+") do |f| f.each do |line| line.split(" ").grep(/#{input}/i).each do |string| match = string.match(/^ipc-(?<bng>[a-z]{3}\d{3})-r-br(?<nr>-\d{2})$/) devices << match[:bng] + match[:nr] end end end (I also think using match instead of scan makes things a bit clearer)...

Use “and” many times in loop in Python [closed]

python,while-loop

In spite of the fact that something is short-circuiting (and stops evaluation at the first falsy result), there's a more concise way to write this using all: while all([A1 == 0, A2 == 0, A3 == 0, A4 == 0]): # Work here While all of the values being generated...

What is the error in this python program?

python,python-2.7,while-loop

If you only want the (root, power) pair with the smallest root value possible, then: try: while root < user_input: root = root + 1 pwr = 1 for power in range(5): if root ** power == user_input: pwr = power raise Found except Found: print output() If you want...

While loop keeps printing out and not reading the next line

c++,printing,while-loop

You need to use brackets #include <iostream> #include <string> using namespace std; int main() { string userName; cout << "Hello there.\n"; cout << "My name is TARS. \n"; cout << "What is your name? \n"; getline(std::cin, userName); cout << userName << ", let's play a game.\n"; int secretNum; secretNum =...

Simple Python Program - unsure with Range and loop

python,for-loop,while-loop,range

Your line for NoOfGamesPlayed != NoOfGamesInMatch: is not valid Python. If you wanted to use looping here, for is helpful but you need to add a range() function: for NoOfGamesPlayed in range(int(NoOfGamesInMatch)): See the Python tutorial on the for construct. Since the input() function returns a string, you need to...

Plain JavaScript + bluebird promises asynchronous for/while loop WITHOUT USING NODE.JS

javascript,for-loop,while-loop,promise,bluebird

Well, once something is a promise returning function - you don't really care about the environment the library takes care of it for you: Promise.delay(1000); // an example of an asynchronous function See this question on converting functions to promise returning ones. Now, once you have that sort of function...

Looping distinct values from one table through another without a join

sql,sql-server,tsql,while-loop

So you want all distinct records from table1 paired with all records in table2? That is a cross join: select * from (select distinct * from table1) t1 cross join table2; Or do you want them related by date? Then inner-join: select * from (select distinct * from table1) t1...

Bash while loop stops unexpectedly

linux,bash,while-loop

Your loop with read after pipe is terminating after first iteration because of invocation of SIGPIPE signal which happens LHS of pipe writes to a pipe whose output is not read as there is no while loop around read on RHS). YOur example with cat doesn't exit because cat continuously...

loop for file location until file exists in bash

bash,file,loops,while-loop,echo

Write the error to stderr echo "File does not exist, please try again" >&2 You are saving all output from the function into the variable tempLoc, so even if the user inputs a valid file it will have a load of junk in the variable with it. Stderr is where...

Php code does not come out from MySQL Database properly

php,mysql,while-loop,phpmyadmin,echo

Please modify your table value ok, your code in sql INSERT INTO `right_widgets` (`right_widgets_id`, `func_name`, `active_status`) VALUES (1, '<?php get_search_engine(); ?>', 'true'), (2, '<?php get_clock(); ?>', 'true'), (3, '<?php get_virtual_nav_menu(); ?>', 'false'), (4, '<?php get_non(); ?>', 'false'); That's mean you table cols name is func_name and value is <?php get_search_engine();...

checking if list has only letters . Python

python,list,function,while-loop

You're entering strings with a space ("first last"), which isalpha() flags as non alphabetic characters. Try this: s = raw_input('> ') names = s.split() good_input = True for name in names: if not name.isalpha(): good_input = False break You need to split by a space and then check with each...

Matlab: Looping through an array

matlab,loops,for-loop,while-loop,do-while

You could do this using conv without loops avg_2 = mean([A(1:end-1);A(2:end)]) avg_4 = conv(A,ones(1,4)/4,'valid') avg_8 = conv(A,ones(1,8)/8,'valid') Output for the sample Input: avg_2 = 0.8445 5.9715 -0.6205 -3.5505 2.5530 6.9475 10.6100 12.5635 6.4600 avg_4 = 0.1120 1.2105 0.9662 1.6985 6.5815 9.7555 8.5350 avg_8 = 3.3467 5.4830 4.7506 Finding Standard Deviation...

counting characters in the input with while loop

c,loops,while-loop,char,eof

while (getchar() != '\n') ++nc; printf("%ld \n",nc); Worked! Thank you very much!...

Change if statement from variable [closed]

c#,if-statement,for-loop,while-loop

context1 is an int since you have assigend an int to it here: int currentField = field; var context1 = currentField; but later you are assigning a bool, f.e here: context1 = currentField % 10 != 0; The !=-operator either returns true or false, so you cannot assign it to...

My While True loop is getting stuck in python

python,while-loop,raspberry-pi,infinite-loop,raspbian

You need to keep updating your input_* variables inside your while loop while True: input_A = GPIO.input(26) input_B = GPIO.input(19) input_C = GPIO.input(13) input_D = GPIO.input(6) if input_A == True: print('A was pushed') if input_B == True: print('B was pushed') if input_C == True: print('C was pushed') if input_D ==...

How to write my program without loops

matlab,function,math,for-loop,while-loop

Copy A to B and then multiply the elements not divisible by k by k: A=[1 2;3,4]; k=2; A1=A/k; B=A; B(A1-fix(A1)~=0)=B(A1-fix(A1)~=0)*k; Edit: Also without using an extra array, similar to eventHandler's idea: B=A; B(mod(A,k)~=0)=B(mod(A,k)~=0)*k ...

Converting fopen to curl using while loop

php,curl,while-loop

You could use explode to split the data into individual lines and iterate through the resulting array using a foreach loop: foreach(explode("\n", $data_from_curl) as $line){ ... } (replace "\n" by "\r\n" if your file uses windows line break)...

c# error: is a 'field' but is used as a 'type' when trying to use while loop [closed]

c#,while-loop

You cannot write code directly within a class. You Need to write it inside a method, e.g. private void Test() { List<int> fib = new List<int>(); bool notAtLimit = true; while (notAtLimit) { //code to populate list of fibonacci series } } ...

Java 'do while' loop not working

java,loops,while-loop

Each time you call nextDouble() the user will enter a double and press enter. This will put a double and a newline in the buffer. The double is consumed by nextDouble(), but the newline character lingers around until you call nextLine(). In your case this becomes a problem, because when...

while loop not looping / displaying count

java,while-loop

I presume your parser.getCommand(); is blocking until there is input. As this while loop runs in one thread, the program is stopped at this point. The easiest way to check if I'm right is to enter any command, and you should get some output from this line: System.out.println(stopWatch.getTime() + "...

Looping through a Vector

arrays,r,loops,vector,while-loop

You can obtain the vector you need with the sapply function: data.frame(x=2:10, iters=sapply(2:10, function(x) length(t5(x))-1)) # x iters # 1 2 1 # 2 3 7 # 3 4 2 # 4 5 5 # 5 6 8 # 6 7 16 # 7 8 3 # 8 9 19...

how can I be more efficient

matlab,for-loop,indexing,while-loop

This gives the same results as your code: TimeLagM = [6;2;3;1;2;10;25;60;2;5;10;80;24;1;2;3]; thresh = 30; maxBack = 3; p=0; count=zeros(length(TimeLagM),1); for i=maxBack+1:length(TimeLagM) p = TimeLagM(i); s = 0; while (s < maxBack && p < thresh) s = s + 1; p = p + TimeLagM(i-s); end if p > thresh...

Matlab: For loop with window array

arrays,matlab,math,for-loop,while-loop

In the meanSum line, you should write A(k:k+2^n-1) You want to access the elements ranging from k to k+2^n-1. Therefore you have to provide the range to the selection operation. A few suggestions: Use a search engine or a knowlegde base to gather information on the error message you received....

How to return a value inside of while loop

c#,while-loop,return-value

If you want to use exactly this solution you can use yield return instead of return statement. But you will need to iterate over the result of Accept() method outside of it. But it is good to use event based solution for this type of code structure. public class Program...

How to combine multiple while True function processes?

python,function,python-2.7,while-loop,python-multiprocessing

Difficult to tell without knowing what exactly you want to achieve with that code, but maybe you do not need processes or thread alltogether. Have you tried generator functions instead? def p1(a=0): while True: yield a a = a + 1 def p2(b=0): while True: yield b b = b...

While loop running incorrect number of times

java,random,while-loop,boolean

You must initialize finished to false if you want to enter the while, and after, when job is done set finished to true to exit the loop boolean finished = false; while (!finished) { // ↑ ↑ ↑ ↑ ↑ →→→→→→ this means loop while finished == false randomNumber1 =...

Python 2.7: While loop, can't break out

python,sockets,python-2.7,while-loop

The while-break- logic is fine. Part one of the problem is in the s.recv(1024) call, which (depending on the socket settings) may block until that many bytes arrived, see http://linux.die.net/man/2/recv: If no messages are available at the socket, the receive calls wait for a message to arrive, unless the socket...

Square root algorithm in python [duplicate]

python,while-loop

You shouldn't use != or == operators to compare floating point variables, as it's improbably you'll ever hit the exact square root with such a naive algorithm. Instead, you should define the acceptable error you're willing to tolerate and continue until you've hit a number with a smaller error than...

Beginner While loop error in MySQL

mysql,loops,while-loop

Your query is all correct except you forgot using brackets around nRomm. Try this, mysql> DELIMITER $$ mysql> CREATE PROCEDURE insertRooms() -> BEGIN -> DECLARE nRoom INT DEFAULT 101; -> WHILE nRoom < 109 DO -> INSERT INTO simple_room (room_number) VALUES(nRoom); -> SET nRoom = nRoom + 1; -> END...

tiered while loops with multiple outputs

list,loops,python-3.x,while-loop

It's hard to tell exactly what you are asking, but I think you just wanted to randomly assign the numbers 3, 4, and 5 somewhere inside your matrix with the condition that i is not divisible by 3 and j is not divisible by 7. If that's what you want,...

Ruby post match returning Nil.. like its supposed too

ruby-on-rails,ruby,string,while-loop

The error isn't the fact that parent_pic_first is nil, the problem is that /\"hiRes\":\"/.match(parent_pic_first) is nil. You're attempting to call a method post_match on a nil value. nil.post_match is quite obviously not going to work. You need to add in some checks to prevent calling post_match on a nil, so...

Can't get my function to run more than once and break my code

javascript,while-loop

while(playerWins === 5 || computerWins === 5) Your while loop will actually never execute, since you're checking for equality and both playerWins and computerWins are 0 initially. You may be looking for a condition more like this: while(playerWins < 5 && computerWins < 5) Note that we're using the logical...

Generate list of 200,000 hashes and save to file

python,while-loop

Discover what you're doing wrong: Open the interactive shell, type bits of your script: >>> import random >>> >>> random.SystemRandom() <random.SystemRandom object at 0x03FD83C8> It's not a number, it's not text. You can't write it to a file. Look at the docs: https://docs.python.org/2/library/random.html#random.SystemRandom It's a random number generator. You need...

while loop is not breaking even if the condition is satisfied

c,loops,while-loop,iteration

You are using same variable (i) for both loops, and in the inner loop the condition of exit is i being 0 or negative, but the only change in this variable in the inner loop is i=i/10 which usually gives unexpected results when using with int. Also, the i will...

while(*s++=*t++) is equivalent to which expression?

c,loops,while-loop

A.) vs. B.) B will always copy the first value before checking if the result is 0. A will do the test first, and if the result is 0, it will stop before ever copying the first value. C.) vs. B.) Similar to A, C does the test first, and...

How to show mysql multi row / mysql_fetch_array results in a table?

php,mysql,arrays,table,while-loop

First of all I think you dont need 3 different queries for your solution.. <table class="table-fill"> <thead> <tr> <th class="text-left">Name</th> <th class="text-left">From</th> <th class="text-left">Agreed Time</th> </tr> </thead> <?php $result = mysql_query('SELECT name,country,agreed_time FROM van_sharing WHERE date = "'.$serch_text.'"') or die(mysql_error()); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { ?> <tr> <td> <?php echo...

Updating jTextArea in while loop

java,swing,while-loop,jtextarea,updating

Correction: This won't help since the infinite loop will still block the EDT forever... Nevermind! Your while loop is a really bad idea, but if you insist, you can at least give the EDT a chance to update the UI by dispatching your append asynchronously: SwingUtilities.invokeLater(new Runnable() { @Override public...

While loop counter increasing “exponentially” in spite of using ++

javascript,while-loop,counter,nested-function

You calculate the next date based on $start_date and counter. However, in the while-loop $start_date is reassigned and thus not represent the start date anymore. Therefore it should not be incremented with counter, but only with one. A correct solution would be: while ($start_date !== $end_date) { var x =...

set a variable to only accept certain strings on python and break while loops using if/else [closed]

python,if-statement,while-loop,except

After some help from various users in the comments section and from @Joe R I have found an answer to this problem: while True: question=input("do you like maths?") while True: re_do=input("Would you like to check anything else?") if re_do.lower=="no": quit() elif re_do.lower=="yes": break elif re_do.lower() !="no" and re_do.lower() !="yes": print("Yes...

How to save each line in a text file as new file

awk,while-loop

awk -F'\t' '$1!=prev{close(out); out=$1".txt"; prev=$1} {sub(/[^\t]+\t/,""); print > out}' file ...

How do I format the logic for 3 conditions and use a previous condition as well?

java,loops,if-statement,while-loop,logic

The second condition should be changed, otherwise the third if won't be reached. Also the third condition should be changed to check if the daysLate variable is greater or equal to zero: if (daysLate > 90) { costDue = bookPrice + 10; } else if (daysLate >= 7) { costDue...

Ending While loop with blank line(Enter key) inside SwitchCase

java,while-loop,switch-statement,blank-line

I'm not 100% sure, but I think that scanner is not reading all input. There's a blank line (a newline character) in the buffer when the Scanner starts to read, so it returns an empty line, which causes your line length to be 0 and exit the loop immediately. Here's...

Loop PHP check until text within webpage has been found

php,file,loops,while-loop,find

On pressing the submit button, I want the PHP code to check to see if a string exists within a webpage on another website. If I understood your question correctly, try this: $content = file_get_contents($url); if(str_replace($string, "", $content) != $content) echo "found"; EDIT: do { $content = file_get_contents($url); }...

Repeat a sound/action every certain time

python,date,time,while-loop,repeat

Your logic is wrong. First of all, the while loop will most likely end in the first iteration and you want the program to continue till you tell it to. In addition to that, you don't update the now variable inside the loop, which is basically a bad idea. For...

Unexpected behavior from “fgets” in a while loop

c,osx,while-loop,fgets

The code compiled normally with a define of MAX_LINE_SIZE = 14. I tried several different ways of getting your output, and the only way that I could was to replace the space char in your input "AAAAAAA BBBBBBBBBB" with ^M. So you may want to look at your input file...

Java Scanner not reading newLine after wrong input in datatype verification while loop

java,while-loop,java.util.scanner

You are reading too much from the scanner! In this line while (sc.nextLine() == "" || sc.nextLine().isEmpty()) you are basically reading a line from the scanner, comparing it (*) with "", then forgetting it, because you read the next line again. So if the first read line really contains the...

Simple Javascript prompt validation loop not working

javascript,html,while-loop,do-while

I would use a boolean value: var name = false; do { name = prompt("Please enter your full name",''); } while(!name); // While name is not true Also you were re-declaring the name var again on within the do loop, remove the var in the loop....

How to make sure to draw two different random cards [closed]

python,loops,random,while-loop

There are three different options you have to choose from here, I will explain each one: Option 1 - break while first_draw == second_draw: first_draw = random.choice(card_values) + random.choice(card_classes) second_draw = random.choice(card_values) + random.choice(card_classes) break break will end the innermost loop. In this case, the loop will only run once....

Redirection based on variables assigned within while loop setup

shell,while-loop,do-while

You actually need redirection inside the while loop: while read -r line; do { cmd1; cmd2; cmd3; } > "/home/Logs/Sample_${line}_$(date +"%Y%m%d_%H%M%S").log" done < "$file" When you have > outfile after done then output is redirected to one file only....

Ruby code efficiency

ruby,while-loop,do-while

Refactored a bit :) loop do print "Please enter valid numbers (between 1 and 12): " possibleSet = gets.chomp break unless possibleSet.split(" ").map(&:to_i).any? {|e| (e<0 || e>12)} end ...

Not entering while loop? [closed]

c++,while-loop,mergesort,insertion-sort

The conditional in while (insertionSortTime < mergeSortTime) is false in the first iteration when both insertionSortTime and mergeSortTime are set to zero. That explains why the loop never got executed. Perhaps you meant to use: while (insertionSortTime <= mergeSortTime) ...

Getting my program to go back to the “top” (if statement) (Java)

java,if-statement,while-loop,leap-year

You're on the right track with a while statement. It's pretty simple to keep it from executing infinitely. As soon as the user enters a correct year, the loop condition will evaluate to false and exit. System.out.println("Enter a year after 1750:"); leapYear = in.nextInt(); while(leapYear < 1750){ System.out.println("You have entered...

Can someone help me explain this code that is converting decimal fractions into a binary?

python,while-loop,binary,floating-point,decimal

I don't think this code is written all that well, but here's a rough idea. The first while loop: while ((2**p)*x)%1 != 0: ... is figuring out how many places in binary to the right of the decimal point will the result be. To use a familiar analogy let's work...

Using a scanner loop across classes (Java)

java,debugging,while-loop,java.util.scanner

I made it more simpler. Please try this. I removed other unknown methods from my code. Scanner sc = new Scanner(System.in); int bet = 0; do { bet=sc.nextInt(); } while (bet > cash); return bet; Say if you pass cash as 100, then you typed 200 as bet, it will...

getchar() not working in c

c,while-loop,char,scanf,getchar

That's because scanf() left the trailing newline in input. I suggest replacing this: ch = getchar(); With: scanf(" %c", &ch); Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than...

While loop won't exit Java

java,loops,while-loop,exit

If you want to implement break for an empty line, get the line trim and check if empty. Your way: while ((line = read.readLine()) != null){ if(line.trim().equals("")){ break; } hold = hold.concat(line); } Using Scanner instead: ... Scanner in = new Scanner(System.in); while(in.hasNextLine()){ String line = in.nextLine(); if(line.trim().equals("")){ break; }...

trying to get a running time stamp on Qt

c++,qt,while-loop

The reason the UI isn't updating is that you never cede control to the event loop, so the main thread doesn't have a chance to update the UI until after your code has executed. There's two possible solutions here: Move your existing code to a background thread that fires a...

Ruby .each method on Array from split string

arrays,ruby,while-loop,split,each

The return statement in ruby is used to return one or more values from a Ruby Method. So your method will exit from return words. def my_function(str) words = str.split return words # method will exit from here, and not continue, but return value is an array(["good", "morning"]). return words[words.count-1]...

Javascript play multiple audio in loop

javascript,audio,while-loop

the mistake you are making, you are not waiting for ended event of the audio before starting the next one, also I am assuming that you are not showing the controls for the audio elements, then you can simplify it as a single audio element and do something like: Number:...

python while loop non-exit

python,python-2.7,loops,while-loop

Kirk is right. raw_input() produces strings, not numeric values. I suspect that balance was also created using raw_input(), is that so? If so, you are comparing string to a string, while you think you compare numbers. That is why you are stuck in this loop. Make sure you have the...

Run PHP function in While Loop

php,function,loops,while-loop

You can simply call your own function generateCode() like any other function inside your loop: while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) { $gencode = generateCode(8); // the rest of your code } Just make sure that generateCode() is already defined when you call it....

using getopts did not get the input value

bash,while-loop,getopts

Try doing: while getopts ":n:f:h" opt; because -n and -f takes argument while -h doesn't....

beginner :While loop not working as it should

c++,loops,vector,while-loop

You over-complicated your loop. Try something more like this instead: #include <vector> #include <string> #include <algorithm> using namespace std; // RL: omitting actual "bad" words to protect the innocent... const vector <string> bwords { "word1", "word2", "word3" }; string bleepWordIfBad(const string &word) { if (std::find(bwords.begin(), bwords.end(), word) != bwords.end()) return...

Buffered Reader read text until character

java,file,while-loop,bufferedreader,readline

It would be much easier to do with a Scanner, where you can just set the delimiter: Scanner scan = new Scanner(new File("/path/to/file.txt")); scan.useDelimiter(Pattern.compile(";")); while (scan.hasNext()) { String logicalLine = scan.next(); // rest of your logic } ...

switch does nothing on Decompiled Android Source

android,for-loop,while-loop,apk,decompiler

Based only on the code posted, it's impossible to say. Most likely you're using a bad decompiler and it gave incorrect output. A lot of the older decompilers aren't very good. Have you tried Procyon or Krakatau? Also, if possible, please post the apk you're trying to analyze....

How do I get my logic in this Java program to make my loop work?

java,if-statement,while-loop,int,logic

Try setting min and min2 to Integer.MAX_VALUE. Practically this should solve your problem because the data type of integers you are working with is int. But theoretically, setting min and min2 to the first input value is the correct solution. EDIT: As a matter of fact, I see that you...

Understanding while in python

python,while-loop,nested

Borrowing from Short Description of Python Scoping Rules Python's scoping rules are really quite simple to remember: Local -- Any local scope; e.g: a function Enclosing -- Any enclosing scope, ee.g: def g(): inside def f() Global -- Any declared "globals", e.g: global x Builtin -- Any builtin function(s), `.eg:...

Javascript alert wont dismiss (while loop)

javascript,html,while-loop

First issue, fix your typo: you use a mix of guesess and guesses they must all be the same. Second issue, once the code is 'giving up', it isn't setting the flag to break the loop. You can use break after the alert to break the loop: alert("i give up");...

How to generate a random number with fixed length only with 0's and 1's and a fixed amount of 1's?

php,loops,random,while-loop,numbers

This should work for you: No need for a loop. Just first fill an array with 1's $many times. Then array_merge() the array with the 0's which you fill up until $length elements. At the end just shuffle() the array and implode() it to print it <?php $min = 0;...

2 while loops follow one another? [closed]

python,while-loop

Yes, of course. Just put your statements in the order you want them to execute, as usual. while (something): pass print(whatever) while (another thing): pass ...

How many times are primitive data types allocated inside loops?

c++,while-loop,allocation,variable-declaration,value-initialization

Logically, yes, the variables are being created at the start of the loop body for every iteration of the loop, and destroyed at the end. In your first example, the constructor of std::string (actually std::basic_string<char> which is what std::string is) will be invoked for every iteration, as will the destructor....

CSV export only heading Arrays not Data

php,mysql,csv,while-loop

what about writing out the same way while in the loop? header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=DepReport_'.$from.'_'.$to.'.csv'); $output = fopen('php://output', 'w'); fputcsv($output, array('Reference', 'Depart Date / Time', 'Depart Terminal', 'Depart Flight' ) ); $i = 2; while($rows = mysql_fetch_array($result)) { //change to $output so it writes lines to same handler...

Pygame nested while loop: [Errno 10054] An existing connection was forcibly closed by the remote host

python,while-loop,pygame

You need to call pygame.event.pump() inside your inner while loop to ensures that your program can internally interact with the rest of the operating system. # .... while a: pygame.event.pump() keys2 = pygame.key.get_pressed() # do something ... An alternative would be to listen for pygame.KEYDOWN events on the event queue...

While Loop increment issue

python,while-loop

The issue is not exactly in your while loop , but in your functions - Output() , Sku() , Material() and Country() . In the function Output() , you are printing the values by directly calling Sku(), etc. In each of the function, I will take one as example -...

Timed while loop not terminating [duplicate]

java,timer,while-loop,timertask

According to Java Memory Model there's no guarantee when non-volatile field will be visible from another thread. In your case your main method is JIT compiled and JIT-compiler reasonably assume that as current thread does not modify the running variable in a loop, then we should not bother reading it...

unix awk column equal to a variable

bash,variables,unix,awk,while-loop

You are passing the shell variables to the awk command using a wrong method. It should be like awk -v a="$a" -v b="$b" '$1==a && $10 == b' What it does -v a="$a" creates an awk variable a and assigns the value of shell variable $a to it. -v b="$b"...

Why this while loop cannot print 1,000 times per seconds?

java,loops,time,while-loop

Try System.nanoTime() since you are not measuring time since the epoch. System.currentTimeMillis vs System.nanoTime

While Loop Problems: Math in SQL

sql,sql-server,tsql,while-loop

That's not a sound SQL design - use a tally table instead like this: with E1(N) AS ( select N from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1) )E1(N) ), --10E+1 or 10 rows E2(N) as (select 1 from E1 a cross join E1 b), --10E+2 or 100 rows E4(N) as (select 1 from E2...

How to query multiple php values into a javascript variable

javascript,php,wordpress,google-maps,while-loop

json_encode supports complex values, you can do: <?php $args = array('post_type' => 'events'); $my_query = new WP_Query($args); locations = array(); while ($my_query->have_posts()) : $my_query->the_post(); $locations[] = array( "lat" => get_field( "gp_latitude" ), "lng" => get_field( "gp_longitude" ), ); endwhile; ?> <script> var locations = <?php echo json_encode($locations) ?>; </script> I...

While statement has no body?

java,loops,syntax,while-loop

Just add an empty body. Like this while( x + ++flips < 8 && board[x + flips][y] == opponent ){}.

while loop in table [closed]

php,sql,while-loop,user

<?php $account = 'Account:'; $password1 = 'Password:'; //check db connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Take everything from table and fill in $result $sql = "SELECT * FROM login"; $result = $conn->query($sql); echo"<table><tr><td>Username</td><td>Password</td><td>Action</td></tr>"; if ($result->num_rows > 0) { // Take all data while($row = $result->fetch_assoc())...

Problems with while() loop [duplicate]

java,while-loop

You are directly comparing arrays resulting in an infinite loop. Those results are being printed but are going to be at the top of tons and tons of output. Fix your comparison.

Nested foreach loop in a While loop can make the condition for the while loop go over?

php,loops,foreach,while-loop

Glad you found an answer. Here is something I was working on while you found it. // SET START DATE $startDate = new DateTime($dateStart); $nextBill = new DateTime(); for($i=1;$i<$countDays;$i++){ switch(true){ case ($startDate->format('j') > $days[2]): // go to next month $nextBill->setDate( $startDate->format('Y'), $startDate->format('m')+1, $days[0]; ); break; case ($startDate->format('j') > $days[1]): //...

How to format code so while loop is triggered C

c,while-loop,formatting,boolean-logic

If scanf fails when reading an integer, the input buffer needs to be cleared of the character causing the failure. The scanset "%*[^\n]" scans and discards characters that are not newline. A newline is left in the input buffer but the %d format specifier will skip leading whitespace. #include <stdio.h>...

How to swap digits in java

java,for-loop,while-loop

public static int swapDigitPairs(int number) { int result = 0; int place = 1; while (number > 9) { result += place * 10 * (number % 10); number /= 10; result += place * (number % 10); number /= 10; place *= 100; } return result + place *...

While loop inside a while loop from PDO query

php,while-loop

No you don't need a second loop , you can use !empty() . it will return false if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable . it will be useful in your case and in case you allow FLAGS to have NULL...

While loop w/ if statement won't follow sucesive if statements

java,string,if-statement,while-loop

When you added your player two options, it looks like you copied over the if statements and forgot to convert the choice.equals for the lower case options to choiceTwo.equals if(choiceTwo.equals("A") || choiceTwo.equals("a")){ pileA = pileA - amount; System.out.println("A: "+pileA+" B: "+pileB+" C: "+pileC); } else if(choiceTwo.equals("B") || choiceTwo.equals("b")){ pileB =...