我目前正在学习Java,并且有一个使用while循环来指示用户输入2个字符串的任务,它会一直提示,直到两个字符串的第一个和最后一个字符相同。我目前在底部有一段代码。当我满足条件时,打印出“宾果”罚款。然而,当我进入while循环时,无论我输入什么输出,它都会保留在我输入的块中,并且是无限循环。我的while条件是否存在问题,或者是while循环中的if条件?
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!");
}
}