Search Results

Search found 4036 results on 162 pages for 'nested loops'.

Page 35/162 | < Previous Page | 31 32 33 34 35 36 37 38 39 40 41 42  | Next Page >

  • Why won't this piece of my code write to file

    - by user2934783
    I am developing a c++ banking system. I am able to get the float, newbal, values correctly and when I try to write to file, there is no data in the file. else { file>>firstname>>lastname; cout<<endl<<firstname<<" "<<lastname<<endl; cout<<"-----------------------------------\n"; string line; while (getline(file, line)) { //stringstream the getline for line string in file istringstream iss(line); if (iss >> date >> amount) { cout<<date<<"\t\t$"<<showpoint<<fixed<<setprecision(2)<<amount<<endl; famount+=amount; } } cout<<"Your balance is $"<<famount<<endl; cout<<"How much would you like to deposit today: $"; cin>>amountinput; float newbal=0; newbal=(famount+=amountinput); cout<<"\nYour new balance is: $"<<newbal<<".\n"; file<<date<<"\t\t"<<newbal; //***This should be writing to file but it doesn't. file.close(); The text file looks like this: Tony Gaddis 05/24/12 100 05/30/12 300 07/01/12 -300 //Console Output looks like this Tony Gaddis 05/24/12 100 05/30/12 300 07/01/12 -300 Your balance is: #1 How much wuld you like to deposit: #2 Your new balance is: #1 + #2 write to file close file. //exits to main loop:::: How can I make it write to file and save it, and why is this happening. I tried doing it with ostringstream as well considering how I used istringstream for the input. But it didn't work either :\ float newbal=0; newbal=(famount+=amountinput); ostringstream oss(newbal); oss<<date<<"\t\t"<<newbal; I am trying to self teach c++ so any relevant information would be kindly appreciated.

    Read the article

  • Need help with this question: Write Java code which reads numbers from the keyboard.....

    - by Chris
    Write Java code which reads numbers from the keyboard until zero is entered. Only the positive numbers entered are to be added to a variable-sized collection. This is what I have so far: import java.lang.*; import java.util.*; import java.io.*; import java.net.*; public class Demo1App extends Object { public static void main(String[] argStrings) throws Exception { ArrayList myArrayList = new ArrayList(); Scanner input = new Scanner(System.in); System.out.println ("NUMBERS:"); while (int input > 0) { myArrayList.add(input); } while (int input < 0) { System.out.println ("ENTER NUMBERS GREATER THAN 0!"); } } } This code doesn't work, I'm not sure why but any help with it would be appreciated.

    Read the article

  • Python2.7: How can I speed up this bit of code (loop/lists/tuple optimization)?

    - by user89
    I repeat the following idiom again and again. I read from a large file (sometimes, up to 1.2 million records!) and store the output into an SQLite databse. Putting stuff into the SQLite DB seems to be fairly fast. def readerFunction(recordSize, recordFormat, connection, outputDirectory, outputFile, numObjects): insertString = "insert into NODE_DISP_INFO(node, analysis, timeStep, H1_translation, H2_translation, V_translation, H1_rotation, H2_rotation, V_rotation) values (?, ?, ?, ?, ?, ?, ?, ?, ?)" analysisNumber = int(outputPath[-3:]) outputFileObject = open(os.path.join(outputDirectory, outputFile), "rb") outputFileObject, numberOfRecordsInFileObject = determineNumberOfRecordsInFileObjectGivenRecordSize(recordSize, outputFileObject) numberOfRecordsPerObject = (numberOfRecordsInFileObject//numberOfObjects) loop1StartTime = time.time() for i in range(numberOfRecordsPerObject ): processedRecords = [] loop2StartTime = time.time() for j in range(numberOfObjects): fout = outputFileObject .read(recordSize) processedRecords.append(tuple([j+1, analysisNumber, i] + [x for x in list(struct.unpack(recordFormat, fout))])) loop2EndTime = time.time() print "Time taken to finish loop2: {}".format(loop2EndTime-loop2StartTime) dbInsertStartTime = time.time() connection.executemany(insertString, processedRecords) dbInsertEndTime = time.time() loop1EndTime = time.time() print "Time taken to finish loop1: {}".format(loop1EndTime-loop1StartTime) outputFileObject.close() print "Finished reading output file for analysis {}...".format(analysisNumber) When I run the code, it seems that "loop 2" and "inserting into the database" is where most execution time is spent. Average "loop 2" time is 0.003s, but it is run up to 50,000 times, in some analyses. The time spent putting stuff into the database is about the same: 0.004s. Currently, I am inserting into the database every time after loop2 finishes so that I don't have to deal with running out RAM. What could I do to speed up "loop 2"?

    Read the article

  • Loop function works first time, not second time

    - by user1483101
    I'm creating a parsing program to look for certain strings in a a text file and count them. However, I'm having some trouble with one spot. def callbrowse(): filename = tkFileDialog.askopenfilename(filetypes = (("Text files", "*.txt"),("HTML files", ".html;*.htm"),("All files", "*.*"))) print filename try: global filex global writefile filex = open(filename, 'r') print "Success!!" print filename except: print "Failed to open file" ######This returns the correct count only the first time it is run. The next time it ######returns 0. If the browse button is clicked again, then this function returns the ######correct count again. def count_errors(error_name): count = 0 for line in filex: if error_name == "CPU > 79%": stringparse = "Utilization is above" elif error_name == "Stuck touchscreen": stringparse = "Stuck touchscreen" if re.match("(.*)" + "Utilization is above" + "(.*)",line): count = count + 1 return count Thanks for any help. I can't seem to get this to work right.

    Read the article

  • Whats wrong with this while loop?

    - by David
    boolean r = false ; int s = 0 ; while (r == false) ; { s = getInt() ; if (!(s>=0 && s<=2)) System.out.println ("try again not a valid response") ; else r = true ; } The text never displays itself even when a 3 or a 123 is entered and the loop never terminates. Whats wrong here?

    Read the article

  • Shell halts while looping and 'transforming' values in dictionary (Python 2.7.5)

    - by Gus
    I'm building a program that will sum digits in a given list in a recursive way. Say, if the source list has 10 elements, the second list will have 9, the third 8 and so on until the last list that will have only one element. This is done by adding the first element to the second, then the second to the third and so on. I'm stuck without feedback from the shell. It halts without throwing any errors, then in a couple of seconds the fan is spinning like crazy. I've read quite a few posts here and changed my approach, but I'm not sure that what have so far can produce the results I'm looking for. Thanks in advance: #--------------------------------------------------- #functions #--------------------------------------------------- #sum up pairs in a list def reduce(inputList): i = 0 while (i < len(inputList)): #ref to current and next item j = i + 1 #don't go for the last item if j != len(inputList): #new number eq current + next number newNumber = inputList[i] + inputList[j] if newNumber >= 10: #reduce newNumber to single digit newNumber = sum(map(int, str(newNumber))) #collect into temp list outputList.append(newNumber) i = i + 1 return outputList; #--------------------------------------------------- #program starts here #--------------------------------------------------- outputList = [] sourceList = [7, 3, 1, 2, 1, 4, 6] counter = len(sourceList) dict = {} dict[0] = sourceList print '-------------' print 'Level 0:', dict[0] for i in range(counter): j = i + 1 if j != counter: baseList = dict.get(i) #check function to understand what it does newList = reduce(baseList) #new key and value from previous/transformed value dict[j] = newList print 'Level %d: %s' % (j, dict[j])

    Read the article

  • Identify words with ascending characters from text file

    - by user2914000
    I am having a fair amount of trouble trying to write a program that counts the amount of ascending words (words in which each character is larger than the previous character) in a text file. I have tried a few different methods to solve this but cannot seem to get it working. If anyone could help me revise the code to work properly it would be appreciated. The code will print about 5 of the words from the list of nearly 20000, but none considered are ascending (the file does have many ascending words) and it sometimes prints the same word twice. I am printing theWord to the console simply to see if the code works. import java.util.Scanner; import java.io.*; public class { public static void main (String [] args) throws FileNotFoundException{ String theWord; Scanner inputFile = new Scanner(new File("file.txt")); boolean ascending = true; int i = 1; while(inputFile.hasNextLine()){ theWord = inputFile.nextLine(); if(theWord.length() >= 2){ while(i < theWord.length() - 1){ if(theWord.charAt(i) <= theWord.charAt(i + 1)){ ascending = true; System.out.println("+ " + theWord); totalNum = totalNum + 1; } else{ ascending = false; System.out.println("= " + theWord); } i++; } } }

    Read the article

  • Best way to make sure I get all available options array/loop

    - by jaz872
    OK, here is my problem. I'm looking for the best way to loop through a bunch of options to make sure that I hit all available options. Some detail. I've created a feature that allows a client to build images that are basically other images layered on top of each other. These other images are split up into different groups. They have links on the side of the image that they can click to scroll through all the different images to view them. I'm now making an automated process that is going to run the function that changes the image when a user clicks one of the links. I need to make sure that every possible combo of the different images is hit during this process. So I have an array with the number of options for each group. The current array is [3, 9, 3, 3] My question is what is the best way to loop through this to make sure that all possible options will be shown? I apologize if this seems simple for someone out there, but I'm just having trouble wrapping my head around it. Hopefully if that person is out there, they can give a helping hand :)

    Read the article

  • Is it faster to count down that it is to count up?

    - by Bob
    Our computer science teacher once said that for some reason it is more efficient to count down that count up. For example if you need to use a FOR loop and the loop index is not used somewhere (like printing a line of N * to the screen) I mean that code like this : for (i=N; i>=0; i--) putchar('*'); is better than: for (i=0; i<N; i++) putchar('*'); Is it really true? and if so does anyone know why?

    Read the article

  • putting data from a for loop into a table using matlab and fprintf

    - by user2928537
    I am trying to put the following data from my for loop into a table formatted so that there are 11 values of F in each column, with a total of 4 columns. but I am always ending up with one long column of my data instead of the four columns I want. I was wondering if there is some way to put the data into a matrix and then reshape it, but I am having trouble. Any help greatly appreciated. fprintf ('Electrostatic Forces:\n') for r = 1:4; q2 = 0: 1*10^-19: 1*10^-18; for F = coulomb(q2,r); fprintf ('%d\n',F) end end Where the code for the function coulomb is function F = coulomb (q2,r); k = 8.98*10^9; q1 = 1.6*10^-19; F = k*abs(q1*q2)/r^2; end

    Read the article

  • C# return and display syntax issue

    - by thatdude
    I am having trouble passing the return value from TheMethod() to Main and displaying the word if the if statement is passed as true. I have thought of two ways of doing this, neither has worked but I think I am missing synatx. Using a return ?; non void method and then displaying the returned value. Using a void method and actually writing out(example below) So yes I am new at this, however I have made so many iterations everything is blending together and I have forgot what I have tried. Any help on the syntax be great for either of these ways. Basically I need it to iterate numbers 1,2,3,4 and depending on if the current iteration matches an expression in the if statements it will display a word. Example: if (3 = i) { Console.WriteLine("Word"); } Code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Proj5 { class Program { int i = 0; static void Main(int i) { for (i = 0; i < 101; i++) { Console.WriteLine("test"); } } string TheMethod(int i) { string f = "Word1"; string b = "Word2"; if (i == 3) { return f; } if (i == 5) { return b; } if (0 == (i % 3)) { return f; } if (0 == i % 5) { return b; } else { return b; } } } }

    Read the article

  • Running C++ functions simultaneously

    - by user2974881
    My code is similar to the following: int main() { values(); } int values() { if (condition) { 'code' } else if (condition) { 'code' } else { 'code' } motors(); } int motors() { 'code' } motors() needs values from values() to run. What could I do so that values() and motors() run simultaneously, side by side, and keep running until the user exits out of the program?

    Read the article

  • DOMDocument::load in PHP 5

    - by Abs
    Hello all, I open a 10MB+ XML file several times in my script in different functions: $dom = DOMDocument::load( $file ) or die('couldnt open'); 1) Is the above the old style of loading a document? I am using PHP 5. Oppening it statically? 2) Do I need to close the loading of the XML file, if possible? I suspect its causing memory problems because I loop through the nodes of the XML file several thousand times and sometimes my script just ends abruptly. Thanks all for any help

    Read the article

  • Why does this while terminate before receiving a value? (java)

    - by David
    Here's the relevant code snippet. public static Territory[] assignTerri (Territory[] board, String[] colors) { for (int i = 0; i<board.length; i++) { // so a problem is that Territory.translate is void fix this. System.out.print ("What team controls ") ; Territory.translate (i) ; System.out.println (" ?") ; boolean a = false ; while (a = false) { String s = getIns () ; if ((checkColor (s, colors))) { board[i].team = (returnIndex (s, colors)) ; a =true ; } else System.out.println ("error try again") ; } System.out.print ("How many unites are on ") ; Territory.translate (i) ; System.out.println (" ?") ; int n = getInt () ; board[i].population = n ; } return board ; } As an additional piece of information, checkColor just checks to make sure that its first argument, a string, is a string in one of the indexes of its second argument, an array. It seems to me that when the while the method gets a string from the keyboard and then only if that string checks out is a true and the while allowed to terminate. The output I get though is this: What team controls Alaska ? How many unites are on Alaska ? (there is space at the end to type in an input) This would seem to suggest that the while terminates before an input is ever typed in since the first line of text is within the while while the second line of text comes after it outside of it. Why is this happening?

    Read the article

  • Python: Closing a for loop by reading stdout

    - by user1732102
    import os dictionaryfile = "/root/john.txt" pgpencryptedfile = "helloworld.txt.gpg" array = open(dictionaryfile).readlines() for x in array: x = x.rstrip('\n') newstring = "echo " + x + " | gpg --passphrase-fd 0 " + pgpencryptedfile os.popen(newstring) I need to create something inside the for loop that will read gpg's output. When gpg outputs this string gpg: WARNING: message was not integrity protected, I need the loop to close and print Success! How can I do this, and what is the reasoning behind it? Thanks Everyone!

    Read the article

  • How to get jquery to append output immediately after each ajax call in a loop

    - by david_nash
    I'd like to append to an element and have it update immediately. console.log() shows the data as expected but append() does nothing until the for loop has finished and then writes it all at once. index.html: ... <body> <p>Page loaded.</p> <p>Data:</p> <div id="Data"></div> </body> test.js: $(document).ready(function() { for( var i=0; i<5; i++ ) { $.ajax({ async: false, url: 'server.php', success: function(r) { console.log(r); //this works $('#Data').append(r); //this happens all at once } }); } }); server.php: <?php sleep(1); echo time()."<br />"; ?> The page doesn't even render until after the for loop is complete. Shouldn't it at least render the HTML first before running the javascript?

    Read the article

  • how to print numbers using for loop in java?

    - by Balkrushn Viroja
    I have one text box in which I take the value of how many number do you want to print. Now My question is that how can I use for loop so that the number which I want to print is equal to the number that I got from textbox.One more thing is that i want to print only three numbers in one line. i.e. If I got 14 in my text box the result will look like below. 1 2 3 4 5 6 7 8 9 10 11 12 13 14

    Read the article

  • Python: Determine whether list of lists contains a defined sequence

    - by duhaime
    I have a list of sublists, and I want to see if any of the integer values from the first sublist plus one are contained in the second sublist. For all such values, I want to see if that value plus one is contained in the third sublist, and so on, proceeding in this fashion across all sublists. If there is a way of proceeding in this fashion from the first sublist to the last sublist, I wish to return True; otherwise I wish to return False. In other words, for each value in sublist one, for each "step" in a "walk" across all sublists read left to right, if that value + n (where n = number of steps taken) is contained in the current sublist, the function should return True; otherwise it should return False. (Sorry for the clumsy phrasing--I'm not sure how to clean up my language without using many more words.) Here's what I wrote. a = [ [1,3],[2,4],[3,5],[6],[7] ] def find_list_traversing_walk(l): for i in l[0]: index_position = 0 first_pass = 1 walking_current_path = 1 while walking_current_path == 1: if first_pass == 1: first_pass = 0 walking_value = i if walking_value+1 in l[index_position + 1]: index_position += 1 walking_value += 1 if index_position+1 == len(l): print "There is a walk across the sublists for initial value ", walking_value - index_position return True else: walking_current_path = 0 return False print find_list_traversing_walk(a) My question is: Have I overlooked something simple here, or will this function return True for all true positives and False for all true negatives? Are there easier ways to accomplish the intended task? I would be grateful for any feedback others can offer!

    Read the article

  • Why does this while terminate before recieving a value? (java)

    - by David
    here's the relevant code snippet. public static Territory[] assignTerri (Territory[] board, String[] colors) { for (int i = 0; i<board.length; i++) { // so a problem is that Territory.translate is void fix this. System.out.print ("What team controls ") ; Territory.translate (i) ; System.out.println (" ?") ; boolean a = false ; while (a = false) { String s = getIns () ; if ((checkColor (s, colors))) { board[i].team = (returnIndex (s, colors)) ; a =true ; } else System.out.println ("error try again") ; } System.out.print ("How many unites are on ") ; Territory.translate (i) ; System.out.println (" ?") ; int n = getInt () ; board[i].population = n ; } return board ; } as an additional piece of information, checkColor just checks to make sure that its first argument, a string, is a string in one of the indexes of its second argument, an array. it seems to me that when the while the method gets a string from the keyboard and then only if that string checks out is a true and the while allowed to terminate. The output i get though is this: What team controls Alaska ? How many unites are on Alaska ? (there is space at the end to type in an input) This would seem to suggest that the while terminates before an input is ever typed in since the first line of text is within the while while the second line of text comes after it outside of it. why is this happening?

    Read the article

  • Accessing nested HashMaps in Java

    - by mridang
    Hi, I have a HashMap in Java, the contents of which (as you all probably know) can be accessed by HashMap.get("keyname"); If a have a HashMap inside another HashMap i.e. a nested HashMap, how would i access the contents? Can i do this like this, inline: HashMap.get("keyname").get("nestedkeyname"); Thank you.

    Read the article

  • C# - Coding a nested stateflow diagram

    - by weberc2
    I have the following state diagram. I know how to make a simple state machine that transitions between non-nested states; however, I don't know how to transition between nested states. Could someone explain how to do this at an appropriately high level (i.e., you don't need to write the code for me--unless you're feeling particularly generous :P). State Diagram [EDIT: The bottom "A", "C", and "E" should be "B", "D", and "F" respectively; sorry!] What I know how to do public class MyState : State // State enumeration { public static MyState A = new MyState("State A"); public static MyState B = new MyState("State B"); public static MyState C = new MyState("State C"); public static MyState D = new MyState("State D"); public static MyState E = new MyState("State E"); public static MyState F = new MyState("State F"); public static MyState NEUT = new MyState("Neutral"); public static MyState P = new MyState("P"); protected MyState(string name) : base(name) { } } public class MyEvent : Event // Event enumeration { public static MyEvent X_POS = new MyEvent("X+"); public static MyEvent X_NEG = new MyEvent("X-"); public static MyEvent Y_POS = new MyEvent("Y+"); public static MyEvent Y_NEG = new MyEvent("Y-"); protected MyEvent(string name) : base(name) { } } public class MyStateMachine : StateMachine<MyState, MyEvent> // State Machine implementation { public MyStateMachine() : base(MyState.P) // MyState.P = initial state { // Set up the transition table // P this.addTransition(MYState.P, MyState.NEUT, MyEvent.Y_NEG); // NEUTRAL this.addTransition(MyState.NEUT, MyState.P, MyEvent.Y_POS); this.addTransition(MyState.NEUT, MyState.A, MyEvent.Y_NEG); this.addTransition(MyState.NEUT, MyState.B, MyEvent.Y_POS); this.addTransition(MyState.NEUT, MyState.C, MyEvent.Y_NEG); this.addTransition(MyState.NEUT, MyState.D, MyEvent.Y_POS); this.addTransition(MyState.NEUT, MyState.E, MyEvent.Y_NEG); this.addTransition(MyState.NEUT, MyState.F, MyEvent.Y_POS); // A this.addTransition(MyState.A, MyState.NEUT, MyEvent.Y_POS); // B this.addTransition(MyState.B, MyState.NEUT, MyEvent.Y_NEG); // C this.addTransition(MyState.C, MyState.NEUT, MyEvent.Y_POS); // D this.addTransition(MyState.D, MyState.NEUT, MyEvent.Y_NEG); // E this.addTransition(MyState.E, MyState.NEUT, MyEvent.Y_POS); // F this.addTransition(MyState.F, MyState.NEUT, MyEvent.Y_NEG); } public void move(MyEvent eevent) { try { this.moveNext(eevent); } catch (Exception e) { } } }

    Read the article

  • How to create nested macro in BOO

    - by Neo
    Hi, I am creating nested macros in BOO, I wrote this program: macro text: macro subMacro: text["Text"] = "Hello World" return [| block: System.Console.WriteLine( "Hello World" ); |] But I am getting the error "Unknown Identifer: 'text'" in the 3rd line of the code.

    Read the article

< Previous Page | 31 32 33 34 35 36 37 38 39 40 41 42  | Next Page >