我正在嘗試爲我的課程之一完成一個項目,而且我幾乎完成了,但遇到了問題。爲此,我能夠得到一些工作,但我不確定應該如何將其分解爲所需的類。分解成Java類
最終的項目應該有一個GuessApp類,它使用GuessLogic(我認爲是正確的)來運行簡單的猜謎遊戲,它處理遊戲的邏輯。換句話說,GuessApp類不會追蹤正確的答案,猜測的數量,之前猜到的數字,或者猜測是否合法。另一方面,GuessApp類負責所有的I/O。換句話說,GuessLogic類不打印任何東西(除了可能用於調試的目的)。
所以我的問題基本上是如何分解我的代碼到這兩個類中,我們也應該在你的GuessLogic類中實現一個toString方法,該方法返回GuessLogic對象的狀態(也就是它的所有成員變量)作爲單個字符串。我將如何做到這一點?
我的代碼迄今:
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
int guess;
int NumGuess = 1;
do {
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
if (hs.contains(guess)) {
System.out.println("You have already entered this number");
continue; // this will repeat the loop
}
if (guess < 0 || guess > 10) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue; // this will repeat the loop
}
System.out.println("Your guess is " + guess);
if (guess == GuessLogic) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
return; // this will stop the loop
}
else if (guess < GuessLogic) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
NumGuess++;
}
else if (guess > GuessLogic) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
NumGuess++;
}
hs.add(guess);
} while (true);
}
}
我認爲你想研究的一般方法是從用戶界面中分離出實際的內容。以這種方式來看待它 - 你可以打印到'System.out'中,或者你可以把它放在一個Swing應用程序或一個Web應用程序中......在任何這些情況下,GuessLogic都不會改變,而UI代碼會。因此,創建一個GuessLogic,例如,有一個'makeGuess(int)'方法,並且您的UI代碼會調用它。像這樣的東西。合理? – dcsohl
Idk我仍然困惑 – bigpappaflex