下面的代码按我希望的方式工作。我只是想知道我是否使用了必要的内存而不是太多内存。我想进入编程作为我的职业生涯,所以很高兴听到那里的一些专业人士。
import java.util.*;
public class GuessingGame {
public static void main(String[] args) {
int counter = 0, number, guess, yes = 1, no =2, answer;
Scanner input = new Scanner(System.in);
number = ((int) (Math.random() * 100));
System.out.println("Would you like to play the guessing game?");
System.out.println("Enter " + yes + " for yes, and enter " + no + " for no");
answer = input.nextInt();
if(answer == no) {
return;
} else {
while (answer == yes) {
System.out.println("Welcome to the guessing game");
System.out.println("There has been a number between 1 and 100 picked \n You have five chances to guess the number");
System.out.print("Please enter your guess >> ");
guess = input.nextInt();
while (guess != number) {
if (guess != number) {
counter = ++counter;
}
if (counter == 5) {
System.out.println("You have used all your guesses");
System.out.println("The number was " + number);
System.out.println("Would you like to play again?");
System.out.println("Enter " + yes + " for yes and " + no + " for no");
answer = input.nextInt();
counter = -1;
if (answer == no)
return;
} else if (guess < number) {
System.out.println("You need to guess higher");
System.out.println("You have used " + counter + " guess(es)");
System.out.println("Please enter your new guess");
guess = input.nextInt();
} else if (guess > number) {
System.out.println("You need to guess lower");
System.out.println("You have used " + counter + " guess(es)");
System.out.println("Please enter your new guess");
guess = input.nextInt();
}
}
System.out.println("You win");
System.out.println("Would you like to play again");
System.out.println("Enter " + yes + " for yes and " + no + " for no");
answer = input.nextInt();
if(answer == no)
return;
}
}
}
}
答案 0 :(得分:0)
我不担心内存优化,除非你有内存描述你的应用程序并且它已经发现问题。你的时间就是金钱,通常1 GB的内存比一小时的时间便宜,1 MB的价值几秒钟,1 KB不值得你按一个键,而你甚至不使用1 KB对象。
在一个更大的程序中,我建议您使用jmc
来分析您的应用程序,特别是查看分配率并考虑如何减少它。