Không trả về kết quả biếu thức mong muốn

thufpt

New Member
2/8/21
11
2
3
Hà Nội
chào các bác, em mới học java có ai có thể giải thích giúp em tai sao code này luôn trả về điều kiện else
mặc dù toán tử truyền vào là đúng mà nó cứ hiển thị điều kiện else.

1627983890289.png

Code:
import java.util.Scanner;



public class hello {

        public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

            int numberFirst;

            int numberSecond;

            int calculator=0;

            String operator = "";

            System.out.print("Please enter numberFirst: ");

            numberFirst = scanner.nextInt();

            System.out.print("Please enter numberSecond: ");

            numberSecond = scanner.nextInt();

            scanner.nextLine();

            System.out.print("Please enter a operator: ");

            operator = scanner.nextLine();

            scanner.close();

            switch (operator) {

                case "+":calculator = numberFirst+numberSecond;

                break;

                case "-":calculator = numberFirst-numberSecond;

                break;

                case "*":

                case "x":calculator = numberFirst*numberSecond;

                break;

                case "/":

                case ":":calculator = numberFirst/numberSecond;

                break;

                case "%":calculator = numberFirst%numberSecond;

                break;

                default:

                    System.out.println("you entered th operator: "+operator);

            }

            System.out.println("numberFirst Is: "+numberFirst);

            System.out.println("numberSecond Is: "+numberSecond);

            System.out.println("operator Is: "+operator);

            if(operator=="+" || operator=="-"|| operator=="*" || operator=="x" || operator=="/" || operator==":" || operator=="%") {

                System.out.printf("%d x %d = %d",numberFirst,numberSecond,calculator);

            }else {

                System.out.print("Unknow this operator "+operator+" can't handle.");

              

            }

          
        }

}
 

Joe

Thành viên VIP
21/1/13
3,007
1,335
113
You misunderstand and misuse the built-in method == with a String.

- A String is started and ends with a double quote "
- built-in == is used ONLY for primitive like int, byte, char, etc.
- Object comparison must be used by equals() method

Please start to learn JAVA with the basics like types (int, char, byte, String, object, etc.), reserved words (==, !=, >, >=, etc.) and their usage. Nobody has time to teach you step by step everything of the basics.
 
  • Like
Reactions: thufpt

thufpt

New Member
2/8/21
11
2
3
Hà Nội
You misunderstand and misuse the built-in method == with a String.

- A String is started and ends with a double quote "
- built-in == is used ONLY for primitive like int, byte, char, etc.
- Object comparison must be used by equals() method

Please start to learn JAVA with the basics like types (int, char, byte, String, object, etc.), reserved words (==, !=, >, >=, etc.) and their usage. Nobody has time to teach you step by step everything of the basics.
Thank you for your time but I also try code again by a paragraph and result in a return as expected, so I don't why

1627990188718.png
Code:
public class calculator {
    public static void main(String[] args) {
        String operator = "+";
        int numberFirst =10;
        int numberSecond=12;
        int calculator= numberFirst+numberSecond;
        if(operator=="+" || operator=="-"|| operator=="*" || operator=="x" || operator=="/" || operator==":" || operator=="%") {
            System.out.printf("%d + %d = %d",numberFirst,numberSecond,calculator);
        }else {
            System.out.print("Unknow this operator "+operator+" can't handle.");
            
        }
    }
}
 

Joe

Thành viên VIP
21/1/13
3,007
1,335
113
Pease read my reply carefully:
Object comparison must be used by equals() method
String is an object
Java:
String operator = "+"; // String primitve
if (operator=="+".... // String primitive
String operator = scanner.readLine(); // String object
if (operator.equals("+").... // String Object
And String has TWO forms: Object string and String primitive.
Further, you should learn to distinguish the Object with the preceding final keyword. String is a FINAL object that cannot be reused. If a new value is assigned to a String two things can happen:

I. String primitive:
1) if the value is a literal (e.g me = "Joe Nartca") it is a NEW String primitive.
2) if the value is an object (e.g. scanner.nextLine()) the string becomes a NEW String object.

II. String Object
1) if the value is a literal (e.g me = "Joe Nartca") it becomes a NEW String primitive.
2) if the value is an object (e.g. scanner.nextLine()) the string becomes a NEW String object.

In other words: String always becomes a new String: either primitive or object.
 
Sửa lần cuối:
  • Like
Reactions: thufpt

thufpt

New Member
2/8/21
11
2
3
Hà Nội
Pease read my reply carefully:

String is an object
Java:
String operator = "+"; // String primitve
if (operator=="+".... // String primitive
String operator = scanner.readLine(); // String object
if (operator.equals("+").... // String Object
And String has TWO forms: Object string and String primitive.
Further, you should learn to distinguish the Object with the preceding final keyword. String is a FINAL object that cannot be reused. If a new value is assigned to a String two things can happen:

I. String primitive:
1) if the value is a literal (e.g me = "Joe Nartca") it is a NEW String primitive.
2) if the value is an object (e.g. scanner.nextLine()) the string becomes a NEW String object.

II. String Object
1) if the value is a literal (e.g me = "Joe Nartca") it becomes a NEW String primitive.
2) if the value is an object (e.g. scanner.nextLine()) the string becomes a NEW String object.

In other words: String always becomes a new String: either primitive or object.
oh so the operator of two-paragraph is not the same, one is given to String primitive and one is given to String Object, What a profound knowledge.
 
  • Like
Reactions: Joe

Joe

Thành viên VIP
21/1/13
3,007
1,335
113
Well, let me tell you more about String. As said, String can be either a primitive or an object. Object and String can be interchanged from object to primitive and vice versa. Example:
Java:
String prim = "This is a String primitive";
prim = new String("This is a String object"); // <-- now it is an object
prim = "again String primitive"; // <-- back to primitive
The comparison is only safe with == if both comparands are primitive. Otherwise it is very UNSAFE.
The SAFEST comparison is the equals() method because it works with both primitives, both objects or mixed. Example:
Java:
public class TestString {
  public static void main(String... a) throws Exception {
    String joe = "Joe Nartca"; // String primitive
    String JOE = new String("Joe Nartca"); // String objecte
    // UNSAFE
    System.out.println("------------UNSAFE WAY-----------------------------------------");
    System.out.println("cPrimitive(cPrimitive, cPrimitive):"+cPrimitive(joe, "Joe Nartca"));
    System.out.println("cPrimitive(cPrimitive, cObject):"+cPrimitive(joe, JOE));
    System.out.println("cPrimitive(cObject, cPrimitive):"+cPrimitive(joe, "Joe Nartca"));
    System.out.println("cPrimitive(cObject, cObject):"+cPrimitive(joe, JOE));
    // SAFE
    System.out.println("------------SAFE WAY-------------------------------------------");
    System.out.println("cObject(cPrimitive, cObject):"+cObject(joe, JOE));
    System.out.println("cObject(cPrimitive, cPrimitive):"+cObject(joe, "Joe Nartca"));
    System.out.println("cObject(cObject, cPrimitive):"+cObject(joe, "Joe Nartca"));
    System.out.println("cObject(cObject, cObject):"+cObject(joe, JOE));
  }
  // cPrimitive: the unsafe way
  private static boolean cPrimitive(String a, String b) {
    return a == b;
  }
  // cObject: the safest way
  private static boolean cObject(String a, String b) {
    return a.equals(b);
  }
}
equals.png
 
  • Like
Reactions: thufpt

thufpt

New Member
2/8/21
11
2
3
Hà Nội
Well, let me tell you more about String. As said, String can be either a primitive or an object. Object and String can be interchanged from object to primitive and vice versa. Example:
Java:
String prim = "This is a String primitive";
prim = new String("This is a String object"); // <-- now it is an object
prim = "again String primitive"; // <-- back to primitive
The comparison is only safe with == if both comparands are primitive. Otherwise it is very UNSAFE.
The SAFEST comparison is the equals() method because it works with both primitives, both objects or mixed. Example:
Java:
public class TestString {
  public static void main(String... a) throws Exception {
    String joe = "Joe Nartca"; // String primitive
    String JOE = new String("Joe Nartca"); // String objecte
    // UNSAFE
    System.out.println("------------UNSAFE WAY-----------------------------------------");
    System.out.println("cPrimitive(cPrimitive, cPrimitive):"+cPrimitive(joe, "Joe Nartca"));
    System.out.println("cPrimitive(cPrimitive, cObject):"+cPrimitive(joe, JOE));
    System.out.println("cPrimitive(cObject, cPrimitive):"+cPrimitive(joe, "Joe Nartca"));
    System.out.println("cPrimitive(cObject, cObject):"+cPrimitive(joe, JOE));
    // SAFE
    System.out.println("------------SAFE WAY-------------------------------------------");
    System.out.println("cObject(cPrimitive, cObject):"+cObject(joe, JOE));
    System.out.println("cObject(cPrimitive, cPrimitive):"+cObject(joe, "Joe Nartca"));
    System.out.println("cObject(cObject, cPrimitive):"+cObject(joe, "Joe Nartca"));
    System.out.println("cObject(cObject, cObject):"+cObject(joe, JOE));
  }
  // cPrimitive: the unsafe way
  private static boolean cPrimitive(String a, String b) {
    return a == b;
  }
  // cObject: the safest way
  private static boolean cObject(String a, String b) {
    return a.equals(b);
  }
}
View attachment 2813
Yes, I will note
regarding Primitive and Object, I was given an assignment on how to build an app allow planner can plan orders on the lines
Order is a list of data available, then clicking on icon pending it shows all orders not yet plan and called pending lits,
the next step use mouse select one by one order to pull outlines
You can see for the lines below, per order color blue, red is assigned name order
one order including information(Quantity, time standard to do this order)
So what is the problem here, it is very very difficult for me,

I don't know how to convert one order from a pending list to an object and pull it outline
besides that, how to build an interface like so
could you guide me

1628160734232.png

Pending list
1628161746122.png
 

Joe

Thành viên VIP
21/1/13
3,007
1,335
113
The Quy tắc hỗ trợ khi hoạt động trên cộng đồng java says:
  • Nhờ làm dùm, giải đề dùm, xin code mẫu, phân tích dùm, không nỗ lực tự hiện thực các vấn đề cơ bản để tích lũy kinh nghiệm.
  • Post xin hỗ trợ nhưng không thể hiện sự nỗ lực của bản thân, không cho mọi người biết rõ đã code được những gì mà không chạy được như ý, đã tìm kiếm như thế nào mà không có kết quả.
  1. Don't concatenate questions to questions. Please open a NEW thread for a NEW question if it is unrelated to the other questions.
  2. The request is very complex. It requires a good knowledge in SWING, in particularly the JTable and the underlaying DB. So, try with simple SWING program before you start to tackle a complex SWING application.
  3. You have firstly tried and post the problems or exceptions HERE. Read the Quy tắc hỗ trợ khi hoạt động trên cộng đồng java
  4. I don't make an exception for you. Terribly sorry !!!
 
  • Like
Reactions: thufpt