0
 public static void processtrans()throws FileNotFoundException{

      Scanner input = new Scanner(transFile);
      String line = input.nextLine();

      double dollar = 0;
      int transNum = 1;

      while (input.hasNextLine()) {
         int Space = line.indexOf (" ");
         int Space2 = line.indexOf (" ", Space + 1);
         String action = line.substring(0,Space);

         if (action == "ORDER"){

            int Space3 = line.indexOf (" ", Space2);
            String isbn = line.substring(Space + 1, Space2);
            int num = Integer.parseInt(line.substring(Space2 + 1, Space3));
            int custNum = Integer.parseInt(line.substring(Space3 + 1));
            System.out.println("Number= " + num);
            System.out.println("Customer number= " + custNum);
         }
         line = input.nextLine();
      }
   }

While I was debugging this code since it compiles but doesn't print anything I saw that it reads the first line of input separates the first word and puts it in the String action but after that it sees if action is "ORDER" or not then skips everything to the line I don't understand why can someone help me?

amudhan3093
  • 740
  • 9
  • 17
missyj
  • 47
  • 1
  • 1
  • 7
  • 3
    Use String.equals method to compare strings instead of ==. Read related post : http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Juned Ahsan Mar 17 '14 at 05:46

4 Answers4

2

Use equals to compare strings

     if (action.equals("ORDER")){

When you use == , you are comparing the String object instead of the actual string.

As mentioned in the comments, here is a great reference for this

Community
  • 1
  • 1
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
2

The == operator in java compares objects for identity (i.e., it returns true if they both reference the same area of memory). In order to compare objects for equality (i.e., return true if they have the same value), you should use the overloaded equals(Object) method:

if (action.equals("ORDER")) {
   // ...
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

In Java == check whether both reference referring same object or not in memory. To check two string objects are meaningfully equal with their content, you have to use equals() method like below

if (action.equals("ORDER")){
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
0

In Java, using == on a String object actually returns true if both are references to the same Object.

In order to check for String equality, there are a few ways to do this.

Objects have an equals(Object o) method that will usually allow you to compare the objects values and see if they are equal.

In the case of a string,

String foo = "foo";
String bar = "foo";

if(foo.equals(bar)) {
    // Hooray
}

However there is another way of going about this. Some recommend to use a string literal for the test to avoid a NullPointerException.

For Example:

"foo".equals(bar);
Tristan
  • 2,349
  • 16
  • 11