I'm currently learning Java in school, and have an assignment to use a while loop to prompt the user for 2 Strings and it will keep prompting until the first and last chars of both Strings are the same. I currently have the piece of code at the bottom. When i do satisfy the conditions, it prints out "Bingo" fine. However when i go into the while loop, no matter what output i enter, it stays in whichever if block i enter, and is an infinite loop. Is there an issue with my while condition or is it the if conditions within the while loop?
import java.util.*;
public class StringTest2{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter word1: ");
String word1 = sc.nextLine().toUpperCase();
System.out.print("Enter word2: ");
String word2 = sc.nextLine().toUpperCase();
int word1Length = word1.length();
int word2Length = word2.length();
char word1First = word1.charAt(0);
char word1Last = word1.charAt(word1Length - 1);
char word2First = word2.charAt(0);
char word2Last = word2.charAt(word2Length - 1);
while(word1First != word2First || word1Last != word2Last){
if(word1First == word2First && word1Last == word2Last){
System.out.println("Bingo!");
}
if(word1First == word2First || word1Last == word2Last){
System.out.println("Gotcha!");
System.out.print("Enter word1: ");
word1 = sc.nextLine().toUpperCase();
System.out.print("Enter word2: ");
word2 = sc.nextLine().toUpperCase();;
}
if(word1First != word2First && word1Last != word2Last){
System.out.println("Mismatch!");
System.out.print("Enter word1: ");
word1 = sc.nextLine().toUpperCase();
System.out.print("Enter word2: ");
word2 = sc.nextLine().toUpperCase();
}
}
System.out.println("Bingo!");
}
}