I have a program in which I am reading from a text file. Below is an extract of the text file. What I want to do is read the first 3 lines and output the unit number (TD684) to console    |12.233     |2016001     |TD684         |Prof. P           |04/01/2016     |01 |12.233     |2016035     |TD684         |Prof. P           |04/01/2016     |01 |12.233     |2016455     |TD684         |Prof. P           |04/01/2016     |01 |10.456     |2016783     |BT473         |Dr. G             |07/01/2016     |01   Below is the program I use to do this. I have initialized the variable switched to false. The first time the program is run it is supposed to assign TD684 to variable unit. After that it is supposed to check if the next line also had TD684. So ideally it should output TD684 3 times to console. But it only happens once which leads me to believe that the loop is not working.        while (switched == false){         String line = sc.nextLine();         String[] parts = line.split(Pattern.quote("|"));         if (timesrun == 0){           unit = parts[3];           timesrun++;         }         if (parts[3] == unit){           System.out.println(parts[3]);         }else{           switched = true;         }     }   Could someone please tell me the reason why my program is not looping?
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
78827
My brother recently started learning C++. He told me a problem he encountered while trying to validate input in a simple program. He had a text menu where the user entered an integer choice, if they entered an invalid choice, they would be asked to enter it again (do while loop). However, if the user entered a string instead of an int, the code would break. I read various questions on stackoverflow and told him to rewrite his code along the lines of:    #include&lt;iostream&gt; using namespace std;  int main() {     int a;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }     }while(true);     return 0; }   While this worked ok, I also tried a few other ideas: 1. Using a try catch block. It didn't work. I think this is because an exception is not raised due to bad input. 2. I tried if(! cin){//Do Something} which didn't work either. I haven't yet figured this one out. 3. Thirdly, I tried inputting a fixed length string and then parsing it. I would use atoi(). Is this standards compliant and portable? Should I write my own parsing function? 4. If write a class that uses cin, but dynamically does this kind of error detection, perhaps by determining the type of the input variable at runtime, would it have too much overhead? Is it even possible?  I would like to know what is the best way to do this kind of checking, what are the best practices?  I would like to add that while I am not new to writing C++ code, I am new to writing good standards compliant code. I am trying to unlearn bad practices and learn the right ones. I would be much obliged if answerers give a detailed explanation.  EDIT: I see that litb has answered one of my previous edits. I'll post that code here for reference.  #include&lt;iostream&gt; using namespace std;  int main() {     int a;     bool inputCompletionFlag = true;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }         else         {             inputCompletionFlag = false;         }     }while(!inputCompletionFlag);     return 0; }   This code fails on input like "1asdsdf". I didn't know how to fix it but litb has posted a great answer. :)
34084
As the title says, is there an easy way to output two columns to the console in Java?  I'm aware of \t, but I haven't found a way to space based on a specific column when using printf.
106661
I have an input file, say, file1, which appears as follows:  WRITE=2 START=1 SMEAR=0 MIN=6 MAX=100   My problem is to search for the string SMEAR and if the string exists replace the entire line with SMEAR=-5. However, if the SMEAR does not exist, then I need to insert a new line SMEAR=-5. Ultimately the line SMEAR=-5 should appear only once. I can replace the string using sed:   sed -i '/SMEAR/c\SMEAR=-5' file1   Or I can insert the string as a new line    sed -i '10i SMEAR=-5' file1   But how can I combine them based on the existence of the string in the file?  EDIT: Also it would be helpful if I can pass the value of SMEAR as a variable.
122948
I have a text variable of class text that shows something like this when it is returned:  " This is sentence 1. This is sentence 2. This is sentence 3. This is sentence 4."   I want to be able to delete specific lines from the text, without affecting the rest of the variable.  For example: delete {1, 3} to get this result:  "This is sentence 1. This is sentence 3. This is sentence 4."     The method described in this answer has a serious bug:    The linked method to delete lines in a paragraph actually converts all linefeeds in the text variable to returns. In other words, it is impossible to run this code more than once on the same variable.  For example, the following code:  set varText to " This is sentence 1. This is sentence 2. This is sentence 3. This is sentence 4." set varText to do shell script "sed -e '1d;3d' &lt;&lt;&lt; " &amp; quoted form of varText -- Employing the same method on the same variable: set varText to do shell script "sed -e '1d;3d' &lt;&lt;&lt; " &amp; quoted form of varText return varText   returns  ""  Since this method only works correctly if the lines of the text variable are the product of a linefeed (as it should), the problem is not that this method fails to perceive a return as a new line (as I had originally claimed in this question). The problem is that this code introduces a return to the text variable in the first place.    Thus, I want a solution that will allow me to run the same text variable through the solution more than once in the same AppleScript.  In other words, I am looking for a method to remove a specific line from a paragraph that does not have this bug and does not insert a return anywhere in the text.
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
1371
I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference?  A (quite pointless) example in Java:  a) declaration before loop:  double intermediateResult; for(int i=0; i &lt; 1000; i++){     intermediateResult = i;     System.out.println(intermediateResult); }   b) declaration (repeatedly) inside loop:  for(int i=0; i &lt; 1000; i++){     double intermediateResult = i;     System.out.println(intermediateResult); }   Which one is better, a or b?   I suspect that repeated variable declaration (example b) creates more overhead in theory, but that compilers are smart enough so that it doesn't matter. Example b has the advantage of being more compact and limiting the scope of the variable to where it is used. Still, I tend to code according example a.  Edit: I am especially interested in the Java case.
13470
I am a little surprised by the following.  Example 1:  char s[100] = "abcd"; // declare and initialize - WORKS   Example 2:  char s[100]; // declare s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)   I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
86352
I'm interesting in directing the output from two commands to a variable.  I don't want the output to be displayed on the screen, but instead assigned to a variable within my script so that I can use it again.  what I am doing is getting the file size from a directory using the commands seen below:  ls -l /var/spool | wc -c   This command gets me the file size in bytes and displays the output as an integer.  I am interested in getting this integer assigned to a variable of my liking so that I can compare it against another variable later  This doesn't seem to work:  size = ls -l /var/spool | wc -c   Would redirection work?   Like this....  ls -l /var/spool | wc -c &gt; size   Either way I want this numeric output to be assigned to a variable and not displayed on the screen.  Any suggestions are very welcomed!
16147
How do I iterate over a range of numbers in Bash when the range is given by a variable?  I know I can do this (called "sequence expression" in the Bash ):   for i in {1..5}; do echo $i; done   Which gives:     1    2    3    4    5   Yet, how can I replace either of the range endpoints with a variable? This doesn't work:  END=5 for i in {1..$END}; do echo $i; done   Which prints:     {1..5}
4461
This prints 83  System.out.println(0123)   However this prints 123  System.out.println(123)   Why does it work that way?
11028
The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this?  Code:  #include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std;  int main() {     ifstream iFile("input.txt");    // input.txt has integers, one per line      while (!iFile.eof())     {         int x;         iFile &gt;&gt; x;         cerr &lt;&lt; x &lt;&lt; endl;     }      return 0; }   input.txt:  10   20   30   Output:  10   20   30   30   Note: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).
14684
I am trying to perform a mathematical operation with sed, but it continues to treat my variables as strings. The input is of this kind:  $ echo 12 | sed 's/[0-9]*/&amp;+3/' $ 12+3   I'd like to have 15 as output. I need to do the operation and replace its mathematical result in only one passage, because I am running the program as a Python daemon, and I want to avoid passages like redirecting stdout on files, open those files, perform operations, extract the result, do the replacement. To me, sed seems the best to perform all in one line.  I've tried to cast both input and output in various ways like  $ echo 12 | sed 's/[0-9]*/int(&amp;+3)/' $ echo 12 | sed 's/[0-9]*/\int(&amp;+3)/' $ echo 12 | sed 's/[0-9]*/\int(&amp;+3)/'   but the result was always a printing of the second field.
119860
A weird bug was occurring in production which I was asked to look into. The issue was tracked down to a couple of variables being declared within a For loop and not being initialized on each iteration. An assumption had been made that due to the scope of their declaration they would be &quot;reset&quot; on each iteration. Could someone explain why they would not be)? (My first question, really looking forward to the responses.) The example below is obviously not the code in question but reflects the scenario:  Please excuse the code example, it looks fine in the editor preview?? for (int i =0; i&lt; 10; i++) {     decimal? testDecimal;     string testString;      switch( i % 2  )     {         case 0:         testDecimal = i / ( decimal ).32;         testString = i.ToString();             break;         default:             testDecimal = null;             testString = null;             break;     }      Console.WriteLine( &quot;Loop {0}: testDecimal={1} - testString={2}&quot;, i, testDecimal , testString ); }   EDIT: Sorry, had to rush out for child care issue. The issue was that the prod code had was that the switch statement was huge and in some &quot;case&quot;'s a check on a class' property was being made, like if (myObject.Prop != null) then testString = myObject.Stringval... At the end of the switch, (outside) a check on testString == null was being made but it was holding the value from the last iteration,hence not being null as the coder assumed with the variable being declared within the loop. Sorry if my question and example was a bit off, I got the phone call about the day care as I was banging it together. I should have mentioned I compared IL from both variables in and out the loop. So, is the common opinion that &quot;obviously the variables would not be reinitialized on each loop&quot;? A little more info, the variables WHERE being initialized on each iteration until someone got over enthusiastic with ReSharper pointing out &quot;the value is never used&quot; and removed them.  EDIT: Folks, I thank you all. As my first post I see how much clearer I should be in the future. The cause of our unexpected variable assignment can me placed on an inexperienced developer doing everything ReSharper told him and not running any unit tests after he ran a &quot;Code Cleanup&quot; on an entire solution. Looking at the history of this module in VSS I see variables Where declared outside of the loop and where initialized on each iteration. The person in question wanted his ReSharper to show &quot;all green&quot; so &quot;moved his variables closer to assignment&quot; then &quot;Removed redundant assignment&quot;! I don't think he will be doing it again...now to spend the weekend running all the unit tests he missed! How to do mark a question as answered?
9685
I had originally coded the program wrongly. Instead of returning the Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 should = only those numbers between 1 &amp; 20), I have written for the program to display all Fibonacci numbers between a range (ie. startNumber 1, endNumber 20 displays = First 20 Fibonacci numbers). I thought I had a sure-fire code. I also do not see why this is happening.  startNumber = int(raw_input("Enter the start number here ")) endNumber = int(raw_input("Enter the end number here "))  def fib(n):     if n &lt; 2:         return n     return fib(n-2) + fib(n-1)  print map(fib, range(startNumber, endNumber))   Someone pointed out in my Part II (which was closed for being a duplicate - ) that I need to pass the startNumber and endNumber through a generator using a while loop. Can someone please point me in the direction on how to do this? Any help is welcome.    I'm a learning programmer and I've run into a bit of a jumble. I am asked to write a program that will compute and display Fibonacci's Sequence by a user inputted start number and end number (ie. startNumber = 20 endNumber = 100 and it will display only the numbers between that range). The trick is to use it inclusively (which I do not know how to do in Python? - I'm assuming this means to use an inclusive range?).  What I have so far is no actual coding but rather:   Write Fib sequence formula to infinite Display startNumber to endNumber only from Fib sequence.   I have no idea where to start and I am asking for ideas or insight into how to write this. I also have tried to write the Fib sequence forumla but I get lost on that as well.
8442
I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers.  The problem is that I get an exception every time. Apparently it can't find it (I am sure its spelled correctly). When looking through code examples, it doesn't specify the file's entire file path, only the name of the file itself. How would I go about doing that if its necessary?  Also, when reading the file, will the array automatically contain all the lines of the file, or will I have to make a loop which which copies every line to corresponding subscript i?  I've heard of BufferedReader class, what it's purpose, and how does it corelate to reading input?
77376
var i : integer;  i := 1234567;   Given the above, I want the string "1,234,567" as output (assuming UK locale). IntToStr just gives me "1234567". I'm sure there's a one-liner for this, but I can't find it...