Okem
Okem

Reputation: 403

Using String Space

I build simple code for checking equal String, but if I using space in content of String A and content of String B same with String A "using space" the result will be "false".

this may code :

public static void main(String[] args) {
        String A = "I write code";
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Words : ");
        String B = input.next();
        if(A.contentEquals(B)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }

but if I change content of String A without space and content String B same with content of String A the result will be "true" .

My question is how to make the result "True" if String A using space ?

Upvotes: 0

Views: 68

Answers (4)

rock321987
rock321987

Reputation: 11032

you will get a compilation error first of all for using

a.contentEquals(b)

as a and b are not defined

first use

A.contentEquals(B)

and the rest of code

String A = "I write code";
Scanner input = new Scanner(System.in);
System.out.print("Enter Words : ");
String B = input.nextLine();
if(A.contentEquals(B)){
    System.out.println("True");
}else
   System.out.println("False"); 

input.next() terminates as soon as we enter space bar..so we have to use input.nextLine()

Upvotes: 0

vinayknl
vinayknl

Reputation: 1252

Trying using as below ( assuming you have created contentEquals(..) method and having null checks)

     if(a.trim().contentEquals(b.trim())){
        System.out.println("True");
    }else
        System.out.println("False");

Not sure about the contents of contentEquals(..) method, if you are just checking equals, use as below

    if(a.trim().equals(b.trim())){
        System.out.println("True");
    }else
        System.out.println("False");

Upvotes: 0

Cengiz
Cengiz

Reputation: 4867

Use trim()

public static void main(String[] args) {
    String A = "I write code";
    Scanner input = new Scanner(System.in);
    System.out.print("Enter Words : ");
    String B = input.next().trim();
    if(a.contentEquals(b)){
        System.out.println("True");
    }else
        System.out.println("False");
}

Upvotes: 0

Keppil
Keppil

Reputation: 46209

This line:

String B = input.next();

stops reading the input when it encounters a space. If you want to be able to input an entire sentence, use nextLine().

Upvotes: 3

Related Questions