0

Recenlty i wrote this code


import java.util.Scanner;

public class Driver {
    
    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);
        String input, input2,input3;
       
        System.out.println("Customer Service\n1. Write\n2. View\n3. Exit\nYour Choice: ");
        do{
            input = scan.nextLine();
            if(input == "1\n"){
                System.out.print("Title: ");
                input2 = scan.nextLine();
                System.out.print("Description: ");
                input3 = scan.nextLine();
         
            }
            else if(input=="2"){
   
            System.out.println("You press 2");
            }
            else {
                System.err.append("Invalid Input.");
            }
        System.out.println(input);
        
        }while(input!="3");
        System.out.println("Exit program");
        
    }
    
}

When i type 1, the input should be 1. But it shows that input!="1" when compare, why does this happen? (2 and 3 also cant work)

Rin
  • 1
  • 1
  • 1
    You can compare ints (primitives) with `==` but not Strings (objects). But you can make it easier on yourself by declaring `input` as an `int` and doing `input = scan.nextInt()`. Then compare using `if(input == 1) {do something`. – WJS Aug 29 '23 at 01:55
  • 1
    Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Aug 29 '23 at 01:57

0 Answers0