我有一个猜测程序,我试图添加一个计数器。在粗体部分,我有一个柜台。当你猜错时,它会向计数器加1。但是当它打印出来时,无论如何都会打印为0。
public static void firstGame(String Answer, String userGuess, int counter)
{
userInput = new Scanner(System.in);
boolean playgame = true;
while(playgame == true)
{
Answer = "Sam";
lnPrint(" ");
lnPrint("Take a guess at my name! It starts with an S...");
sPrint(":");
userGuess = userInput.next();
if(userGuess.equalsIgnoreCase(Answer))
{
lnPrint("You got it! Its " + Answer);
lnPrint(" ");
break;
}
else if(userGuess != Answer)
{
lnPrint("Good guess, keep trying!");
counter++;
}
}
}
这是我用计数器的游戏方法。
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
int Start, counter = 0;
String Answer, userGuess, middleAnswer, middleUserGuess;
Answer = null;
userGuess = null;
middleAnswer = null;
middleUserGuess = null;
Start = 0;
while(Start !=2)
{
lnPrint("(1) Start Game");
lnPrint("(2) Exit");
sPrint(":");
Start = userInput.nextInt();
if(Start == 1)
{
firstGame(userGuess, Answer, counter);
lnPrint("Now, how about my middle name?");
nlnPrint(counter);
middleGame(middleAnswer, middleUserGuess);
}
这是打印它的代码
答案 0 :(得分:0)
这看起来像值/引用问题的常见传递。使用counter
作为firstGame
的参数时,它是counter
方法中使用的firstGame
的值,如反对将引用传递给counter
变量;你可以在这里阅读,例如:http://www.javacoffeebreak.com/faq/faq0066.html
通过引用方法传递整数的方法(参见Java : Best way to pass int by reference),但在这种情况下,我认为你应该简单地将counter
声明为全局变量。
答案 1 :(得分:-1)
你早些时候初步确定了“反击”吗? 下面是一个有效的例子:
$.Guess = function() {
var parent = this;
var counter = 0;
this.guess = function(val) {
if ( val != 5 ) {
parent.guessedWrong();
}
}
this.guessedWrong = function() {
counter++;
}
this.guessed = function() {
return counter;
}
this.resetCounter = function() {
counter = 0;
}
}
var game = new $.Guess();
game.guess(1);
game.guess(2);
alert( game.guessed() );
game.guess(3);
game.guess(4);
game.guess(5);
// Alerts 4, because there is 5 guesses and one of them (the one with value 5) is correct
alert( game.guessed() );
// Reset counter to 0
game.resetCounter();
game.guess(6);
game.guess(7);
game.guess(8);
alert( game.guessed() );
..上面的代码可以在这里测试:http://jsfiddle.net/jcpjr9dc/