So, I'm not sure what is happening here, if I place encode or decode in the args[0], it should work right, but it doesn't. I have all the imports and I have a utility class that I'm using as well. I don't understand why, when I run the program with these arguments: java Prog4 encode fly message.txt it won't work right. It'll go straight to the last else statement.      public class Prog4 {         public static void main(String[] args){             if (args.length != 3){                     System.out.println("Enter the right amount of arguments!");                     System.exit(0);             }              String command=args[0];             String key= args[1];             String fileName = args[2];             File file = new File(args[2]);             String fileExtention="";             if(args[0]=="encode"){                     fileExtention=".crypt";              }             else if (args[0]=="decode"){                     fileExtention=".decrypt";             }             else{                     System.out.println("Enter decode or encode!");                     System.exit(0);             }
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?
24218
Is this functionality going to be put into a later Java version?  Can someone explain why I can't do this, as in, the technical way Java's switch statement works?
52656
How can I use/display characters like ♥, ♦, ♣, or ♠ in Java/Eclipse?  When I try to use them directly, e.g. in the source code, Eclipse cannot save the file.  What can I do?  Edit: How can I find the unicode escape sequence?
110820
I'm currently making a callout to a 3rd party vendor and I'm getting a huge response. What is currently messing me up is this section:   "MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false   As you can see here, the portion at the end of the Description value is ended with backslash double quote. If I attempt to parse this via the JSONParser I get an exception. Does anyone have an recommendations on how to resolve this?  Exception Message:  System.JSONException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries at [line:1, column:3699]  Updated with sample Code   public class ResponseWrapper{     // fields from JSON to auto map     public Integer messageSeq;     public String Description;     public String messageTS;     public Integer messageLevel;     public Boolean isSystemMessage;     // parsing fields     private ResponseWrapper theResponse;     private JSONParser parser;      public void parse(String jsonString){         parser = JSON.createParser(jsonString);         parseJSON();     }      private void parseJSON(){            while (parser.nextToken() != null) {             if (parser.getCurrentToken() == JSONToken.START_OBJECT) {                 theResponse = (ResponseWrapper)parser.readValueAs(ResponseWrapper.class);                            }         }     } }  String responseString = '{"MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false}'; system.debug('\n\nBEFORE\n' + responseString); ****Place code in here to test such as ReplaceALL*** ResponseWrapper parser = new ResponseWrapper(); parser.parse(responseString);
95851
I have made a Java program that could open any application. Suppose there is a file name "*.jpg", the it would allow the OS to recognize the type of application and then open the default application. Another example: Suppose the file's name is "*.flv", then it would open up the default media player just like when you click an icon in nautilus but the only difference was that it was in command line. Here is the java program for that:  import java.awt.*; import java.io.*; public class OpenFile{     public static void main(String args[]){       try{           String filename = args[0];           System.out.println(args[0]);           Desktop.getDesktop().open(new File(filename));       }       catch(Exception e){           System.out.println("Sorry an exception occured. Could not perform the operation.");       }     }  }   Now this script leads to performance issues. Now I want to write a BASH script to do this task ??
113159
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized?   public static void Main(String[] args) {     Byte maxSize;     Queue queue;      if(args.Length != 0)     {         if(Byte.TryParse(args[0], out maxSize))             queue = new Queue(){MaxSize = maxSize};         else             Environment.Exit(0);     }     else     {         Environment.Exit(0);     }      for(Byte j = 0; j &lt; queue.MaxSize; j++)         queue.Insert(j);     for(Byte j = 0; j &lt; queue.MaxSize; j++)         Console.WriteLine(queue.Remove()); }   So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?  Hope ya'll can give me some pointers :)  Thanks.
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));         }      }
117868
The basic idea that I wanted was to create a key to pass a value that would inform \makebox how the contents of the box should be aligned.  Big fail here.    The intended contents of the \makebox are not passed as arguments to \makebox and I seem to have random components of my keys ignored or inserted into the text.  What's happening here?  \documentclass{article} \usepackage{xparse} \ExplSyntaxOn  \tl_new:N  \l_aefl_position_tl \tl_set:Nn \l_aefl_position_tl { [l] }  \keys_define:nn { aefl }     {         pos   .code:n   = {                             \str_case:nnn { #1 }                             {                                 { left   } { \tl_set:Nn \l_aefl_position_tl {[l]} }                                 { center } { \tl_set:Nn \l_aefl_position_tl {}    }                             }                             {                                 { right } { \tl_set:Nn \l_aefl_position_tl {[r]} }                             }                           },     }  \NewDocumentCommand{\aecurrfile}{ o }     {         \group_begin:         \IfNoValueF{#1}{\keys_set:nn { aefl }{#1}}          \makebox[0pt] \l_aefl_position_tl                       { contents ~ of ~ my ~ box }         \group_end:     }  \ExplSyntaxOff \pagestyle{empty} \begin{document}  \begin{tabular}{lcl} unexpected &amp; \verb=[l]=      &amp; \aecurrfile                        \\ unexpected &amp; \verb=[l]=      &amp; Front \aecurrfile[pos=left] Back   \\            &amp;                 &amp; Front \aecurrfile[pos=center] Back \\ unexpected &amp; \verb=right[l]= &amp; Front \aecurrfile[pos=right] Back \end{tabular}  \end{document}   EDIT  Finally, I see why I'm getting the unexpected right in my output.  Argh!
79610
an example code what I try to do will surely do better than my english:  public bool IsNumericValueInBounds (string value, Type numericType) {   double d = double.NaN;         bool inBounds = (bool)numericType.GetMethod ("TryParse").Invoke (null, new object[] { value, d });    return inBounds; }   Unfortunately the TryParse method needs an out parameter so this doesn't work. any ideas how to solve this?  (ps.: would'nt this be a nice example for duck typing? - because i know every numericType has an "TryParse" or I am mistaken?)
5845
I tried to use java.io.FileReader to read some text files and convert them into a string, but I found the result is wrongly encoded and not readable at all.  Here's my environment:   Windows 2003, OS encoding: CP1252 Java 5.0   My files are UTF-8 encoded or CP1252 encoded, and some of them (UTF-8 encoded files)  may contain Chinese (non-Latin) characters.  I use the following code to do my work:     private static String readFileAsString(String filePath)     throws java.io.IOException{         StringBuffer fileData = new StringBuffer(1000);         FileReader reader = new FileReader(filePath);         //System.out.println(reader.getEncoding());         BufferedReader reader = new BufferedReader(reader);         char[] buf = new char[1024];         int numRead=0;         while((numRead=reader.read(buf)) != -1){             String readData = String.valueOf(buf, 0, numRead);             fileData.append(readData);             buf = new char[1024];         }         reader.close();         return fileData.toString();     }   The above code doesn't work. I found the FileReader's encoding is CP1252 even if the text is UTF-8 encoded. But the JavaDoc of java.io.FileReader says that:     The constructors of this class assume   that the default character encoding   and the default byte-buffer size are   appropriate.   Does this mean that I am not required to set character encoding by myself if I am using FileReader? But I did get wrongly encoded data currently, what's the correct way to deal with my situtaion? Thanks.
24489
#include &lt;stdio.h&gt; #include &lt;conio.h&gt; main() {     char ch,name[20];     int i=0;     clrscr();     printf("Enter a string:");     while((ch=getch())!='\n')     {         name[i]=ch;         i++;     }     name[i] = '\0';     printf("%s",name); }   When I give "abc" as input and if I press enter it's not working. Can anyone let me know why the condition ch=getch() != '\n' is not becoming false when I press enter? I have also observed that ch is taking \r instead of \n. Kindly let me know. Thanks
34476
With reference to the following thread:   What is the best way to programatically determine the correct charset encoding of an inputstream/file ?  I have tried using the following:  File in =  new File(args[0]); InputStreamReader r = new InputStreamReader(new FileInputStream(in)); System.out.println(r.getEncoding());   But on a file which I know to be encoded with ISO8859_1 the above code yields ASCII, which is not correct, and does not allow me to correctly render the content of the file back to the console.
51376
For I school project, I have to implement a shell/terminal app. But I am wondering how are command line options parsed, because it appears abit weird to be. For example for the command paste (and I believe other utilities behave similarly)  [jiewmeng@JM tmp]$ paste --help Usage: paste [OPTION]... [FILE]...   Behavior when combining multiple options into one  [jiewmeng@JM tmp]$ paste -ds file1 file1 xxx file1 d aaws dafd a   Here it appears options are just ignored ...   [jiewmeng@JM tmp]$ paste -sd file1   It behaves the same as paste -, waiting for stdin. But when its valid combination  [jiewmeng@JM tmp]$ paste -sd. file1 file1 xxx.file1.d aaws dafd a   It works. Shouldn't the invalid one give an error instead of waiting for stdin?  [jiewmeng@JM tmp]$ paste -d paste: option requires an argument -- 'd' Try 'paste --help' for more information.   Ok, makes sense d requires an argument, but ...   [jiewmeng@JM tmp]$ paste -d file1   ... waits for stdin. why?
4029
uint color;  bool parsedhex = uint.TryParse(TextBox1.Text, out color);  //where Text is of the form 0xFF0000 if(parsedhex)    //...   doesn't work. What am i doing wrong?
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
31131
Assuming String a and b:  a += b a = a.concat(b)   Under the hood, are they the same thing?  Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.  public String concat(String s) {      int i = s.length();     if (i == 0) {         return this;     }     else {         char ac[] = new char[count + i];         getChars(0, count, ac, 0);         s.getChars(0, i, ac, count);         return new String(0, count + i, ac);     } }
54700
I have a Python script which accepts string arguments.  $ python script.py "one image.jpg" "another image.jpg"   This works as expected.  Python argparse: ["one image.jpg", "another image.jpg"]    If I need to pass filenames I would do,  $ python script.py $(ls "/some/dir/*.jpg")   Python argparse: ["one", "image.jpg", "another", "image.jpg"]  If use the -Q of ls command, I can wrap results between double quotes. However, quotes stay escaped in Python script, ie.  $ python script.py $(ls -Q "/some/dir/*.jpg")   Python argparse: ['"one image.jpg"', '"another image.jpg"']    How should I expand ls filenames into proper strings to use as arguments? (as in my very first example)