在这里玩猜数字游戏,有两种方法可以做到。我可以创建一个名为 Number 的对象类,然后使用 getter 和 setter 等方法number.setPlayerNumber
,然后number.getPlayerNumber
在我的 if 语句中使用来确定获胜者。
这意味着我不需要使用静态变量,它们只会保留在方法的范围内(以后让它不那么麻烦?(但可以让 main 方法看起来很乱?...))
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class NumberGuess {
static Number number = new Number();
static boolean win;
public static void main(String[] args) {
int cpuNumber = generateNumber();
int playerNumber = playerNumber();
printResults();
winCondition();
}
public static int generateNumber() {
System.out.println("Generating a number");
System.out.println("Done!");
Random rand = new Random();
int cpuNumber = rand.nextInt(10) + 1;
number.setCpuNumber(cpuNumber);
return cpuNumber;
}
public static int playerNumber() {
Scanner userInput = new Scanner(System.in);
String playerNum = JOptionPane.showInputDialog(null, "Enter a number between 1 and 10",
"Player Turn", JOptionPane.INFORMATION_MESSAGE);
number.setPlayerNumber(Integer.parseInt(playerNum));
return Integer.parseInt(playerNum);
}
public static void printResults(){
System.out.println("The computers number was: " + number.getCpuNumber());
System.out.println("Your number was: " + number.getPlayerNumber());
}
public static void winCondition(){
if(number.getCpuNumber() != number.getPlayerNumber()){
if(number.getPlayerNumber() < number.getCpuNumber()){
System.out.println("You lose!\n"
+ "Guess too low!");
}else{
System.out.println("You lose!\n"
+ "Guess too high!");
}
}
if(number.getPlayerNumber() == number.getCpuNumber()){
System.out.println("You have guessed correct. You win!");
}
}
}
我也可以继续使用返回方法。这意味着我需要将每个变量设为静态,以便在使用它们进行决策的方法中使用它们。
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class NumberGuess {
static Number number = new Number();
static int cpuNumber = generateNumber();
static int playerNumber = playerNumber();
static boolean win;
public static void main(String[] args) {
printResults();
winCondition();
}
public static int generateNumber() {
System.out.println("Generating a number");
System.out.println("Done!");
Random rand = new Random();
int cpuNumber = rand.nextInt(10) + 1;
return cpuNumber;
}
public static int playerNumber() {
Scanner userInput = new Scanner(System.in);
String playerNum = JOptionPane.showInputDialog(null, "Enter a number between 1 and 10",
"Player Turn", JOptionPane.INFORMATION_MESSAGE);
return Integer.parseInt(playerNum);
}
public static void printResults(){
System.out.println("The computers number was: " + number.getCpuNumber());
System.out.println("Your number was: " + number.getPlayerNumber());
}
public static void winCondition(){
if(cpuNumber != playerNumber()){
if(playerNumber() < cpuNumber){
System.out.println("You lose!\n"
+ "Guess too low!");
}else{
System.out.println("You lose!\n"
+ "Guess too high!");
}
}
if(playerNumber == cpuNumber){
System.out.println("You have guessed correct. You win!");
}
}
}
从良好的编程实践的角度来看,什么更有效?