Okay, so I even printed out the values of the variables that will be compared to the username and password.  Username luke Password: password Username Attempt: luke Password Attempt: [C@5e15c325  But I'm attempting to input 'password'.... The JPasswordField holds a character array, so I have to use the 'toCharArray' when comparing the char [] 'passwordAttempt' and the String 'pass' that holds the password that is held in a file. Maybe this is why the password attempt is some strange value? Here's the code of the login() function:  public void login() {     //booleans for error-handling and user authentication      boolean usersInDatabase = true;     boolean userAuthentication = false;     boolean passwordAuthentication = false;     //create the data reader     try {          reader = new Scanner(user1); //user1 is a file     } catch (FileNotFoundException noUsers) {         JOptionPane.showMessageDialog(window, "No users in the database");         usersInDatabase = false;     }       //variables      String user = "";          //variables that will hold the file data which has the      String pass = "";          //username and password     try {      user = reader.nextLine();         pass = reader.nextLine();     }     //you can skip through the error-handling     catch (NoSuchElementException noUsers) {         JOptionPane.showMessageDialog(window, "No users in the database");         usersInDatabase = false;     }     if (usersInDatabase)     {      String userAttempt = usernameField.getText();     String message = ""; //message to display if authentication is unsuccessful     char[] passwordAttempt = passwordField.getPassword();     //okay -- important stuff     //username authentication       if (userAttempt == user) {         userAuthentication = true;      }     else      message += "Incorrect Username -- ";       //password authentication   if (passwordAttempt == pass.toCharArray()) {        //check to see if the input matches the string (a character array) that has the value of the file     passwordAuthentication = true;  } else  message += "Incorrect Password";    if (passwordAuthentication == true &amp;&amp; userAuthentication == true) {       JOptionPane.showMessageDialog(window, "Authorization Successful");       cards.show(cardPanel, "documents"); } else if(passwordAuthentication == false &amp;&amp; userAuthentication == false)     JOptionPane.showMessageDialog(window, message);        //to print out the values for debugging System.out.println("Username " + user + "\nPassword: " + pass + "\nUsername Attempt: " + userAttempt + "\nPassword Attempt: " + passwordAttempt); }  }
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?
19207
So my 2009 new years resolution is to learn Java.  I recently acquired "Java for Dummies" and have been following along with the demo code in the book by re-writing it using Eclipse.  Anyway, every example in the book that uses a relative path does not seem to read the .txt file it's supposed to read from.  Here is the sample code:  import java.util.Scanner; import java.io.File; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.GridLayout;  class TeamFrame extends JFrame {      public TeamFrame() throws IOException {         PlayerPlus player;         Scanner myScanner = new Scanner(new File("Hankees.txt"));          for (int num = 1; num &lt;= 9; num++) {             player = new PlayerPlus(myScanner.nextLine(), myScanner.nextDouble());             myScanner.nextLine();             addPlayerInfo(player);         }                add(new JLabel());         add(new JLabel("   ------"));         add(new JLabel("Team Batting Aberage:"));         add(new JLabel(PlayerPlus.findTeamAverageString()));         setTitle("The Hankees");         setLayout(new GridLayout(11,2));         setDefaultCloseOperation(EXIT_ON_CLOSE);         pack();         setVisible(true);     }      void addPlayerInfo(PlayerPlus player) {         add(new JLabel(player.getName()));         add(new JLabel(player.getAverageString()));     } }   And you can see in the below screen shot I have included this file.  image no longer available  Also, I have verified that when I build the application that a copy of Hankees.txt is placed in the bin folder with the compiled .class files.  Lastly, if I change line 12 to the following and place Hankees.txt in the root of my C:\ drive the program compiles and runs fine.  Scanner myScanner = new Scanner(new File("C:\\Hankees.txt"));   So basically, my question is what am I doing wrong?  Or is Eclipse responsible for this in some way?  Thanks for any and all help!
22356
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?    string testString = "Test"; string anotherString = "Another";  if (testString.CompareTo(anotherString) == 0) {} if (testString.Equals(anotherString)) {} if (testString == anotherString) {}   (Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)
108487
I have the code below (I've included what I believe are all relevant sections):  private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ? AND VAL_@ = ?;"; public bool read(string id) {     level = -1;     MySqlCommand m = new MySqlCommand(readCommand);     m.Parameters.Add(new MySqlParameter("", val1));     m.Parameters.Add(new MySqlParameter("", val2));     MySqlDataReader r = m.ExecuteReader();     if (r.HasRows)         level = Convert.ToInt32(r.GetValue(0).ToString());     r.Close();     return true; }   When I run this, I get an IndexOutOfBoundsException on adding the first parameter. What have I done wrong?
115517
I wanted to suggest an edit for  given to , but it was denied because "Edits must be at least 6 characters."  However, given the edit I was suggesting is very important to the syntax of the solution, I think it is relevant even though it contains only 3 characters. See the answer posted by knittl and notice the variable $value is used as both function input and in the foreach loop. I simply suggested changing the function parameter's name to $values in the 3 locations it is used, but was denied, leaving the post incorrect.  Note: I do realize I could have suggested an entirely different variable name thus allowing the edit, but similar situations have arisen in the past where a simple fix of just a few characters make a significant difference. After all, Stack Overflow is a coding website and syntax is very important.
54555
Consider the following CSV file:  jdbc.driverClassName,oracle.jdbc.driver.OracleDriver  jdbc.username,kshitiz   It has to be transformed into:  -Djdbc.driverClassName=oracle.jdbc.driver.OracleDriver \  -Djdbc.username=kshitiz \   Given the following bash snippet:  while read l; do     IFS=',' read -ra arr &lt;&lt;&lt; "$l"     echo '-D'${arr[0]}'='${arr[1]}' \' done &lt;properties.txt   Bash prints:  \jdbc.driverClassName=oracle.jdbc.driver.OracleDriver   \jdbc.username=kshitiz   What's going on here?
92456
Alright, I have been doing the following (variable names have been changed):   FileInputStream fis = null; try {     fis = new FileInputStream(file);      ... process ...  } catch (IOException e) {     ... handle error ... } finally {     if (fis != null)         fis.close(); }    Recently, I started using FindBugs, which suggests that I am not properly closing streams.  I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException.  What are people supposed to do here?  The Java libraries throw too many checked exceptions.
38112
Here's the scenario...    if (entry.Properties["something"].Value != null)   attribs.something = entry.Properties["something"].Value.ToString();   While effective and working correctly, this looks ugly to me.  If I don't check for a null before performing the ToString() then it throws an exception if the property was null.  Is there a better way to handle this scenario?  Much appreciated!
104445
I am wondering because I am trying to make sure that person have right amount of spaces for their user name.  User Name and Password are security measures and should not be easy to guess. I have fixed amount of characters to Passwords no shorter than 6 characters because most sites use 6-8 characters when create an account. Because of limitation of my progams database file I cannot have passwords longer than 20 characters. What about User Name field? Too short User Name would be too easy to guess, too long, might cause program errors (since maximum length of single line TextBox in .Net/C# is about 32767 characters).  What should be the maximum and minimum length of User Name and Password fields?
2343
I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.  Is there a better/different way to read a file into a string in Java?  private String readFile(String file) throws IOException {     BufferedReader reader = new BufferedReader(new FileReader (file));     String         line = null;     StringBuilder  stringBuilder = new StringBuilder();     String         ls = System.getProperty("line.separator");      try {         while((line = reader.readLine()) != null) {             stringBuilder.append(line);             stringBuilder.append(ls);         }          return stringBuilder.toString();     } finally {         reader.close();     } }
49686
Sometimes when I am debugging code in Eclipse it happens that although I can see and inspect class member variables without any difficulty I am unable to inspect the values of variables declared locally within functions. As an aside, any parameters to the current function lose their 'real' names and instead one sees their values listed in the Variables window as arg0, arg1, arg2, etc but at least the values are visible.  This is occurring at present in relation to classes defined within the core JDK. I have verified that the installed and current JRE is a JDK.  Is anybody able to shed some light on this behaviour?
16433
What characters are valid in a Java class name? What other rules govern Java class names (for instance, Java class names cannot begin with a number)?
2156
In Java is there a way to check the condition:  "Does this single character appear at all in string x"  without using a loop?
106441
I have a method like this:  public static &lt;T&gt; boolean isMemberOf(T item, T[] set) {     for (T t : set) {         if (t.equals(item)) {             return true;         }     }     return false; }   Now I try to call this method using a char for T:  char ch = 'a'; char[] chars = new char[] { 'a', 'b', 'c' }; boolean member = isMemberOf(ch, chars);   This doesn't work. I would expect the char and char[] to get autoboxed to Character and Character[], but that doesn't seem to happen.  Any insights?
16499
If yes, on which operating system, shell or whatever?  Consider the following java program (I'm using java just as an example, any language would be good for this question, which is more about operation systems):  public class ExitCode {     public static void main(String args[]) {         System.exit(Integer.parseInt(args[0]));     } }   Running it on Linux and bash, it returns always values less equal 255, e.g. (echo $? prints the exit code of the previous executed command)  &gt; java ExitCode 2; echo $? 2  &gt; java ExitCode 128; echo $? 128  &gt; java ExitCode 255; echo $? 255  &gt; java ExitCode 256; echo $? 0  &gt; java ExitCode 65536; echo $? 0     EDITED: the (only, so far) answer below fully  explain what happens on UNIXes. I'm still wondering about other OSes.
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
109143
name=Jackson echo $name   This will display Jackson.  name="Jackson" echo $name   This will also display Jackson.   So I assume by putting quotation marks around a variable it is making it a string. What would name=Jackson technically be? Would it also be recognized as a string?