我正在從事兩種不同類別的牛和公牛遊戲: 第一類看起來像這樣: import java.util。*; import java.util.Scanner;奶牛和公牛遊戲
public class CowsAndBulls {
int UserNumber=0;
int CompNumber=0;
int bulls=0;
int cows=0;
Scanner input = new Scanner(System.in);
public void getUserNumber() {
System.out.println("Please enter your guess!");
int UserValue=input.nextInt();
UserNumber=UserNumber+ UserValue;
System.out.println("Your guess is : " + UserNumber);
}
public void getCompNumber() {
Random generator= new Random();
int pickedNumber=generator.nextInt(10000) + 1000;
CompNumber =CompNumber+ pickedNumber;
System.out.println("The computer has guessed : " + CompNumber);
}
}
它只是爲計算機生成一個隨機數,並要求用戶輸入他們的猜測。 我遇到了很多麻煩,我的戲類,具體而言,我不能讓我的while循環運行,
public class CowsAndBullsPlay {
public void play() {
int GuessCount=0;
int UserNumber = 0;
int CompNumber = 0;
int cows = 0;
int bullcount=0;
int cowcount=0;
int bulls = 0;
Boolean GameEnds;
GameEnds=false;
while (GameEnds=false) {
CowsAndBulls user= new CowsAndBulls();
user.getUserNumber();
CowsAndBulls comp= new CowsAndBulls();
comp.getCompNumber();
String UserString=String.valueOf(UserNumber);
String CompString=String.valueOf(CompNumber);
String U=UserString;
String C=CompString;
for (int i=0; i<4; i++)
for (int k=i+1; k<4; k++) {
if(U.charAt(i)==C.charAt(k)) {
bullcount ++;
bulls=bulls + bullcount;
}
else if(U.contains(C.charAt(i) + U)) {
//for (int v=0; v<4; v++)
//for (int j=0; j<4; j++) {
cowcount ++;
cows=cows + cowcount;
}
GuessCount++;
}
if (bulls==4) {
GameEnds= true;
System.out.println("Congratulations!");
System.out.println("it took you:" + GuessCount);
}
else {
System.out.println("cows: " + cows);
System.out.println("Bulls:" + bulls);
}
}
}
}
它應該檢查奶牛,然後再檢查公牛,那麼公牛是否是不等於四,循環應重申 - 調用前兩個方法,要求用戶輸入並要求計算機隨機生成一個數字,然後guesscount應跟蹤循環迭代。
代碼編譯,但它只是不會運行while循環
這裏是我的測試類:
public class CowsAndBullsTester {
public static void main(String[] args) {
int bears = 0;
int cows = 0;
Boolean GameEnds = false;
System.out.println("welcome to Cows Versus Bulls death match!");
CowsAndBulls user= new CowsAndBulls();
user.getUserNumber();
System.out.println("Now the computer will pick a number!");
CowsAndBulls comp= new CowsAndBulls();
comp.getCompNumber();
System.out.println("Let's see how you did!");
CowsAndBullsPlay game= new CowsAndBullsPlay();
game.play();
}
}
非常感謝所有幫助。我確定有一些愚蠢的錯誤,我只是不確定是什麼。這只是我的第三項任務,而且我在自己的問題上弄錯了什麼是錯誤的:)
謝謝!
更棒的是,只是'while(!GameEnds)' – 2013-03-06 18:41:46
@AndrewMao那也是。 :) – asteri 2013-03-06 18:42:05
謝謝! while循環現在正在運行,但是我有一個字符串索引超出了這個界限的異常:if(U.charAt(i)== C.charAt(k))在遊戲類中。任何爲什麼這是錯誤的?索引必須有問題,但我看不到 – Maddie24 2013-03-06 21:48:06