【发布时间】:2018-06-28 05:29:08
【问题描述】:
所以我有一个制作游戏的任务,我成功了,但它刚刚超过了线数限制。我尝试在不破坏语法规则以及保持正确形式(大括号)的情况下尽可能多地删除空行和其他内容。游戏是计算机生成 4 个数字(1-10)并得到一个最终数字,该数字从 4 个数字(随机 1 或 2)中相加或相减,然后人们需要弄清楚是加还是减每个数字。代码没有问题,只需要缩短一点。 (可能有几行?)
这是我的代码:
//ROHAN DATTA (ICS2O8-C) - Magic Operations Game
import java.util.Scanner;
public class MagicNumberOperations {
public static void main(String[] args) {
int num1, num2, num3, num4, operation, finalAns = 0;
String equation = "", userAns, playAgain;
Scanner input = new Scanner (System.in);
System.out.println("You are now playing: MAGIC NUMBER OPERATIONS");
System.out.println("In this game, the computer generates 4 random numbers (1-10), \nand you must choose which operation (+ or -) to use with each number in order to get the final result (Determined by the computer!)");
do {
num1 = (int)(Math.random()*(10-1+1)+1); //Randomly generating 4 numbers
num2 = (int)(Math.random()*(10-1+1)+1);
num3 = (int)(Math.random()*(10-1+1)+1);
num4 = (int)(Math.random()*(10-1+1)+1);
operation = (int)(Math.random()*(2-1+1)+1);
if (operation == 1) { //Determining whether or not to add or subtract
equation = num1 + "+" + num2; //Making word equation to compare with user answer later
finalAns = num1 + num2; //Creating integer answer to create the final number
}
else if (operation == 2) {
equation = num1 + "-" + num2;
finalAns = num1 - num2;
}
operation = (int)(Math.random()*(2-1+1)+1);
if (operation == 1) {
equation += "+" + num3;
finalAns += num3;
}
else if (operation == 2) {
equation += "-" + num3;
finalAns -= num3;
}
operation = (int)(Math.random()*(2-1+1)+1);
if (operation == 1) {
equation += "+" + num4;
finalAns += num4;
}
else if (operation == 2) {
equation += "-" + num4;
finalAns -= num4;
}
System.out.println("\n\nHere are your 4 numbers: " + num1 + ", " + num2 + ", " + num3 + ", " + num4); //Statements
System.out.println("And here is what all the numbers together should be: " + finalAns);
System.out.print("\nEnter the whole equation (NO SPACES): ");
userAns = input.nextLine();
if (!userAns.equals(equation)) {
System.out.println("Incorrect!");
System.out.println("The correct answer was: " + equation);
break; //If answer is wrong, loop breaks, GAME OVER!
}
System.out.print("Correct! \n\nWould you like to play again (y / n) ?");
playAgain = input.nextLine();
} while (!playAgain.equals("n"));
input.close();
System.out.println("\n\nGAME OVER!");
}
}
【问题讨论】:
-
System.out.println("x")后跟System.out.println("y");可以替换为System.out.println("x\ny"); -
2-1+1 == 2。那为什么要写2-1+1?