Java 如何在每次不按enter键的情况下获取输入?
我做了一个简单的游戏(还不是真正的游戏),玩家可以在一个房间里移动4x20个角色。它在控制台中运行 但在我的游戏循环中,我希望能够在房间里走动,而不必每次都按enter键。玩家应该能够按w/a/s/d并立即更新屏幕,但我不知道怎么做Java 如何在每次不按enter键的情况下获取输入?,java,user-input,Java,User Input,我做了一个简单的游戏(还不是真正的游戏),玩家可以在一个房间里移动4x20个角色。它在控制台中运行 但在我的游戏循环中,我希望能够在房间里走动,而不必每次都按enter键。玩家应该能够按w/a/s/d并立即更新屏幕,但我不知道怎么做 public class Main{ public static void main(String[] args){ MovementLoop(); } public static void MovementLoop(){ Scanner inpu
public class Main{
public static void main(String[] args){
MovementLoop();
}
public static void MovementLoop(){
Scanner input = new Scanner(System.in);
int pos=10, linepos=2;
String keypressed;
boolean playing = true;
while(playing == true){
display dObj = new display(linepos, pos);
dObj.drawImage();
keypressed=input.nextLine();
if(keypressed.equals("w")){
linepos -= 1;
}
else if(keypressed.equals("s")){
linepos += 1;
}
else if(keypressed.equals("a")){
pos -= 1;
}
else if(keypressed.equals("d")){
pos += 1;
}
else if(keypressed.equals("q")){
System.out.println("You have quit the game.");
playing = false;
}
else{
System.out.println("\nplease use w a s d\n");
}
}
}
}
public class display{
private String lines[][] = new String[4][20];
private String hWalls = "+--------------------+";
private String vWalls = "|";
private int linepos, pos;
public display(int linepos1, int pos1){
pos = pos1 - 1;
linepos = linepos1 - 1;
}
public void drawImage(){
for(int x1=0;x1<lines.length;x1++){
for(int x2=0;x2<lines[x1].length;x2++){
lines[x1][x2]="#";
}
}
lines[linepos][pos]="O";
System.out.println(hWalls);
for(int x2=0;x2<lines.length;x2++){
System.out.print(vWalls);
for(int x3=0;x3<lines[x2].length;x3++){
System.out.print(lines[x2][x3]);
}
System.out.println(vWalls);
}
System.out.println(hWalls);
}
}
公共类主{
公共静态void main(字符串[]args){
MovementLoop();
}
公共静态void MovementLoop(){
扫描仪输入=新扫描仪(System.in);
int pos=10,linepos=2;
按字符串键;
布尔播放=真;
while(播放==true){
display dObj=新显示器(linepos,pos);
dObj.drawImage();
keypressed=input.nextLine();
如果(按键等于(“w”)){
linepos-=1;
}
else if(按键等于(“s”)){
linepos+=1;
}
else if(按下键等于(“a”)){
pos-=1;
}
else if(按键等于(“d”)){
pos+=1;
}
else if(按下键等于(“q”)){
System.out.println(“你已经退出了游戏。”);
玩=假;
}
否则{
System.out.println(“\n请使用w a s d\n”);
}
}
}
}
公开课展示{
专用字符串行[][]=新字符串[4][20];
私有字符串hWalls=“+------------------+”;
私有字符串vWalls=“|”;
专用int linepos,pos;
公共显示(int linepos1,int pos1){
pos=pos1-1;
linepos=linepos1-1;
}
公共图像(){
对于(intx1=0;x1来说,答案很简单
你不能那样做
因为命令行环境不同于swing,因为swing可以处理事件和对象,而命令行并没有事件
所以,也许现在正是离开命令行的时候。Boolean zen!永远不要使用while(foo==true)
,只需使用while(foo)
。避免==true
和==false
是一种很好的方式。检查此项的可能重复-