如何在java中创建一个while循环,一旦两个用户输入匹配,该循环将结束游戏



我一直在尝试创建一个游戏,要求用户输入两个三个字母的单词;该程序应该通过将单词拆分并说明字母表中字母是在彼此之前还是之后,来提供单词匹配程度的线索。

游戏快结束了,但当我在一次猜测后试图开始新的回合时,我的问题就出现了。我需要一些while循环,但我已经多次重新排列代码块,我觉得这让整个事情变得更加复杂。每当两个输入不完全匹配时,第二个用户回答问题的提示以及线索都应该重复。

当两个用户输入为cat和fan时的示例输出:after、a、before

;在";显示字母在字母表中位于用户的字母之后;在";显示字母位于用户的字母之前。

编辑我已经尽可能多地考虑了答案,非常感谢到目前为止,我已经实现了一个do while循环,并试图修复我的变量最后,我觉得在某个条件语句设置为false后,我可能必须创建一个对象才能重新复制用户输入的代码

我的新问题是

1.每当我在do while循环中有用户输入时,编译器就找不到符号x1、y1、z1、x2、y2和z2

2.如果我试图创建一个新对象,我将重写&重新安排超出可能需要的范围 这仍然在进行中,随着我继续工作,我会不断更新这篇文章

(编辑代码--我保存了原始代码,可以发送给任何想看它的人。(

import java.util.Scanner;
class Main{
public static void main(String[] args) {
System.out.println("Guess The Wordn(requires two players)");
System.out.println("If the letter in each word matches, the letter will be reprinted.");
System.out.println("If the letter guessed doesn't match, either "before" or "after" will print.");
Scanner in1=new Scanner(System.in);
//Scanner in2=new Scanner(System.in);
try{
boolean correct1=false; boolean correct2=false; boolean correct3=false;
int indication=0;
//asks for user input and stores in substrings
do{
System.out.print("First Player, enter a three letter word: ");
String user1=in1.nextLine();
String x1=user1.substring(0,1);
String y1=user1.substring(1,2);
String z1=user1.substring(2,3);
System.out.print("Second Player, enter a three letter word: ");
String user2=in1.nextLine();
String x2=user2.substring(0,1);
String y2=user2.substring(1,2);
String z2=user2.substring(2,3);
}
while(!correct1||!correct2||!correct3);
//possible end to loop
//      if(user1==user2){indication=1;}
//      else{indication=0;}
//comparisons of each letter
int comp;
int comp2;
int comp3;
comp=x1.compareTo(x2);
comp2=y1.compareTo(y2);
comp3=z1.compareTo(z2);
//while1=(comp!=0);
//while2=(comp2!=0);
//while3=(comp3!=0);
//if statement 1
if(comp==0){
System.out.print(x1);
correct1=true;
}
else{
//        System.out.println(comp);
if(comp>0){
System.out.println("before, ");
}
else{
System.out.print("after, ");
}
}
//if statement 2
if(comp2==0){
System.out.print(y1);
correct2=true;
}
else{
//        System.out.println(comp);
if(comp2>0){
System.out.println(", before, ");
}
else{
System.out.print(", after, ");
}
}
//if statement 3
if(comp3==0){
System.out.print(z1);
correct3=true;
}
else{
//        System.out.println(comp3);
if(comp3>0){
System.out.println(", before");
}
else{
System.out.print(", after");
}
}
//ignore else{System.out.print("Congratulations!");}
}
finally{in1.close();}/* in2.close();}*/
}
}

可能声明3个布尔值(1IsCorrect、2IsCorrect和3IsCorrect(,将它们默认设置为false,并在打印值后的if(comp/comp1/comp2==0(语句中将相应的布尔值设置为true。然后把它放在一段时间内(!1IsCorrect ||!2IsCorrect ||!3IsCorrect(在循环之前为isFirstRun声明一个变量,并在声明中将其实例化为true,然后在最后设置为false。做一个if!isFirstRun语句,并在那里添加代码以请求下一个猜测

希望这能起作用

最新更新