Joe Smith
Joe Smith

Reputation: 41

Why my code doesn't work? - Getting user input to initiate a for loop

So I have this Java assignment, where I must create a program, where if the user enters "initiate" it begins the for loop, which will print "initiated" 100 times. I've searched my code for errors, but can't find any. Please help :)

Thanks in advance.

       package container;

        import java.util.Scanner;

        public class Assignment1 {


    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int x = 0;

        String checker = "initiate";

        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine();     
        if(input == checker){

            for(x=0;x<=100;x++){

                System.out.println("Initiated");

            }
        }   
    }
}

Upvotes: 0

Views: 243

Answers (5)

rgettman
rgettman

Reputation: 178253

As others have pointed out, use the equals method to compare strings:

if(checker.equals(input))

However, also, your for loop will print Initiated 101 times, for values of x from 0 through 100. Replace

for(x=0;x<=100;x++)

with

for(x=0;x<100;x++)

Upvotes: 2

christopher
christopher

Reputation: 27336

if(input == checker)

compares if these two variables have the same object reference. Ie: point to the same object.

if(input.equals(checker))

checks if input has the same content as checker. That is why it's not working :)

Upvotes: 0

user2030471
user2030471

Reputation:

You should be using input.equals(checker) instead of input == checker.

Upvotes: 0

Javier
Javier

Reputation: 12398

You should compare Strings using equals instead of ==

if (input.equals(checker))

Upvotes: 3

PermGenError
PermGenError

Reputation: 46398

 if(input == checker){

should be

 if(input.equals(checker)){

Use equals() method to check if two string objects are equal. == operator in case of Strings(Objects in general) checks if two references refer to the same object

Upvotes: 2

Related Questions