Reputation: 41
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
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
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
Reputation:
You should be using input.equals(checker)
instead of input == checker
.
Upvotes: 0
Reputation: 12398
You should compare Strings using equals
instead of ==
if (input.equals(checker))
Upvotes: 3
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