0

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");

            }
        }   
    }
}
knowbody
  • 8,106
  • 6
  • 45
  • 70
Joe Smith
  • 41
  • 1
  • 4

5 Answers5

3

You should compare Strings using equals instead of ==

if (input.equals(checker))
Javier
  • 12,100
  • 5
  • 46
  • 57
  • The tutorials i was reading never mentioned any of these methods, you have opened a door for me :) thankyou. – Joe Smith Feb 25 '13 at 23:47
2
 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

Community
  • 1
  • 1
PermGenError
  • 45,977
  • 8
  • 87
  • 106
2

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++)
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

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

0
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 :)

christopher
  • 26,815
  • 5
  • 55
  • 89