java控制控制檯裏面輸出的星號的移動

這是我最開始接觸java時寫的第一個java程序,很簡單的一個程序,但卻是我安卓開發之路的開始!希望以後能在安卓開發這條路上好好走下去!

新建java工程,實現利用1、2、3、5按鍵控制星號左移、下移、右移和上移。

實現效果如下:

1.運行程序


2.點擊數字鍵3,點擊enter確定,效果如下,星號右移一位:


3.點擊數字鍵2,點擊enter,效果如下,星號下移一位:


4.其他按鍵均類似;


1.新建Cell類,定義成員變量,實現構造方法和功能方法,代碼如下:

package cellmove;


public class Cell {
int x;
int y;
public Cell(int x,int y){
this.x=x;
this.y=y;
}
public Cell(){
}
public void moveToRight(){
this.x++;
}
public void moveToLeft(){
this.x--;
}
public void moveToTop(){
this.y--;
}
public void moveToBelow(){
this.y++;
}
public int getx(){
return this.x;
}
public int gety(){
return this.y;
}
public void setx(int newx){
this.x=newx;
}
public void sety(int newy){
this.y=newy;
}
}

2.新建CellMove類,代碼如下:

package cellmove;


import java.util.Scanner;


public class CellMove {


public static void main(String[] args) {
int width=5;
int height=5;
Cell cell=new Cell(0,0);
while(true){
Scanner scanner =new Scanner(System.in);
for(int i=0;i<height;i++){
for(int j=0;j<width;j++){
if(i==cell.gety()&&j==cell.getx()){
System.out.print("* ");
}
else
System.out.print("- ");
}
System.out.println();
}
int m1=scanner.nextInt();
if(m1==1&&cell.getx()>0){
cell.moveToLeft();
}
else if(m1==1&&cell.getx()==0){
System.out.println("對不起,星號已位於最左邊,無法左移!");
}
else if(m1==2&&cell.gety()<height-1){
cell.moveToBelow();
}
else if(m1==2&&cell.gety()==height-1){
System.out.println("對不起,星號已位於最下邊,無法下移!");
}
else if(m1==3&&cell.getx()<width-1){
cell.moveToRight();
}
else if(m1==3&&cell.getx()==width-1){
System.out.println("對不起,星號已位於最右邊,無法右移!");
}
else if(m1==5&&cell.gety()>0){
cell.moveToTop();
}
else if(m1==5&&cell.gety()==0){
System.out.println("對不起,星號已位於最上邊,無法上移!");
}
}
}
}


這樣就初步實現了星號的位移;


總結:實現的功能雖然簡單,但正是因爲實現這些簡單地功能,以後才能更好地實現更加複雜的功能,這應該就是所謂的基礎吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章