所以我刚刚在30分钟内完成了这个快速的小型演示游戏,我想知道两件事:
我知道我可以使用课程,但我对他们有点缺乏经验。我对如何从特定类中获取变量感到困惑。我需要将它们导入主方法类吗?
import java.util.Scanner;
public class mainGame
{
public static Scanner kboard = new Scanner(System.in);
public static boolean loop = true;
public static int treesInArea = 0;
public static int day = 0;
public static int wood = 0;
public static int woodCollected = 0;
public static int woodLevel = 0;
public static void main(String[] args)
{
System.out.println("__________________________________");
System.out.println(" Welcome to seul...Lets begin ");
System.out.println(" You woke up in the middle of ");
System.out.println(" a forest. Use the command walk ");
System.out.println(" in order to walk into a new area ");
System.out.println("__________________________________\n");
while(loop == true)
{
String choice = kboard.nextLine();
if(choice.equalsIgnoreCase("walk"))
{
treesInArea = (int)(Math.random() * 20);
System.out.println("__________________________________");
System.out.println("The number of trees in this area is");
System.out.println(treesInArea + " trees");
System.out.println("__________________________________\n");
day++;
System.out.println(" It is day " + day + " ");
System.out.println("__________________________________\n");
System.out.println(" Current usuable commands are : ");
System.out.println(" - Chop tree\n");
} else
if(choice.equalsIgnoreCase("choptree") || choice.equalsIgnoreCase("chop tree"))
{
if(treesInArea < 1)
{
System.out.println("There are no trees in this area.");
} else
{
woodCollected = (int)(Math.random() * 10);
treesInArea --;
wood += woodCollected;
woodLevel += (int)(Math.random() * 2);
System.out.println("__________________________________");
System.out.println(" You collected " + woodCollected + " wood");
System.out.println(" Your total wood = " + wood);
System.out.println(" Your total woodcutting level = " + woodLevel);
System.out.println("__________________________________\n");
}
}
}
}
}
答案 0 :(得分:1)
您可以通过以下四种主要方式改进代码:
1•您的代码缩进不是很好,在类名,循环,if语句等之后应该是4个空格(或者只是按Tab键)缩进。示例:
private methodName() {
for(int i = 0; i < 10; i++;) {
//do something
}
}
2•当方法/循环之后的大括号时,读取代码更容易,并且占用的空间更少,例如(5行简洁代码):
if (condition = true) {
//do something
} else {
//do something else
}
而不是(7行凌乱的代码):
if (condition = true)
{
//do something
} else
{
//do something else
}
因为当你有长if-else
块或长循环时,它会变得难以阅读。
3•您不需要在一行之后添加空格,这不会做任何事情。所以这个:
System.out.println(" It is day " + day + " ");
可以成为这个:
System.out.println(" It is day " + day);
4•最后,组织代码的最佳方式是分割和征服&#34;。这意味着即使它们非常短,也要methods,以防止重复代码并节省时间。例如,您在程序中打印了以下行:System.out.println("__________________________________");
7次。如果您制作如下所示的方法,则可以通过避免重复代码来节省时间和空间,只需使用printDivider();
在您使用此行的任何地方调用该方法:
private static void printDivider() {
System.out.println("__________________________________");
}
是的,我会玩你的游戏(实际上我做了玩你的游戏),但你可以通过添加更多可能性或不同的路径来改进它。下去,结局不同。