Java:试图在Simon游戏中获得用户输入作为Int



我正试图弄清楚为什么1)我的西蒙游戏在说"输入数字"后挂断了——看起来它甚至没有通过验证。我正在尝试获得用户输入,并检查当时按下的数字是否正确。2) 此外,它曾经生成一个随机数,但当用户按下它时,由于某种原因,它返回为false。其他一些随机数也会通过。3) 另外,下面的代码是为你彩色编码的吗?谢谢大家。

import acm.program.*;
import acm.graphics.*;
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.DataInputStream;
public class Simon extends Program implements ActionListener
{
Scanner usersInputScanner = new Scanner(System.in);

private int array[];
private int currentSeqLength;
private int usersInput;
private String usersInputString;

public Simon()
{
//Initialize Class Values
array = new int[20];
currentSeqLength = 1;
usersInput = 0;
generateSequence();
while(currentSeqLength < array.length)
{
playSequence();
//Wait For User's Input, Assign To Variable
System.out.println("Enter A Number");
usersInput = usersInputScanner.nextInt();
if (pushButton(usersInput) == true)
{
System.out.println("You Entered: " + usersInput);
currentSeqLength++;
}
else
{
gameOverMessage();
break;
//Reset Variables:
}
}

}


//----------------------- Methods Here On Down -----------------------------


public void generateSequence()
{
//Fill Array With Random Numbers
for (int i = 0; i < array.length; i++ )
{
array[i] = (int)(Math.random()*4);
}

}
public void setLength(int length)
{
//Set Current Length To Size Of Given Argument
currentSeqLength = length;
}
int getLength()
{
return currentSeqLength;
}
int[] playSequence()
{
//Print Out The Current Sequence
//New Local Array To Return
int newArray[]= new int[currentSeqLength];

//Repeat As Many Times As Value Of currentSeqLength
for(int i = 0; i < currentSeqLength ; i++)
{
System.out.println(array[i]);
//Return an array of int's to the player. 
newArray[i] = array[i];
}
return newArray;
}
boolean pushButton(int usersInput)
{
//Given A Button Press (0-3), Return Whether That Was The 
//Correct Button To Play At The Moment
if (usersInput == array[currentSeqLength])
{
return true;
}
else
{
return false;
}

}

boolean isTurnOver()
{
//If Current Sequence Length Matches Or Exceeds Value Of 
//Array Element In Location Of Current Sequence Length
if (currentSeqLength >= array[currentSeqLength])
{
return true;
}
else
{
return false;
}
}
//Not Needed?
boolean isGameOver()
{
if (pushButton(usersInput) == false)
{
return true;
}
else
{
return false;
}
}
String gameOverMessage()
{
return "Game Over";
}
/*public void actionPerformed(ActionEvent event)
{
int input;

}
*/
}

1)我的Simon游戏在说"输入数字"后挂断了——它没有看起来它甚至通过了验证。

工作正常,但您需要System.out.printlngameOverMessage()返回的字符串。现在,它运行得很好,但没有输出到控制台,所以它看起来没有响应(而且它没有挂起,只是到达执行结束,然后停止)。

else {
gameOverMessage();
break;
}

应该是

else {
System.out.println(gameOverMessage());
}

2)此外,它曾经生成一个随机数,但当用户按下由于某种原因,它被认为是假的。

我在您的示例代码中没有得到这种行为,它看起来像预期的那样工作。

3)此外,下面的代码是否为您进行了颜色编码?

是的,SO上的预览框有时需要一秒钟的时间来突出显示语法。不过效果不错。

顺便说一句,三个问题合一对回答者来说有点吃力。在未来,也许试着把自己限制在一个:)

最新更新