[英]Matching a user input String to an object of a 2D array with the same Name attribute in Java
因此,我創建了一個2D類型的“對象”對象數組,這些對象代表2D 10x10網格上的化身,其中零位表示“開放”點,而Champions顯然沒有零位。
private static void createCharacter()
{
System.out.println("New Character Name");
String name = sc.next();
System.out.println("Character x coord");
int xc = sc.nextInt();
System.out.println("Character y coord");
int yc =sc.nextInt();
Champion tempchamp = new Champion(name,xc,yc);
if(grid[xc][yc]!= null)
{
System.out.println("Error, Space Already Occuped");
}//End If
else
{
grid[xc][yc] = tempchamp;
}//End Else
我的角色構造函數允許使用名稱,x和y坐標,但是顯然,坐標也表示在網格上。 類似於“ Output My”問題的輸出現在正在尋找一種方法,允許用戶選擇他們要移動的角色。 有沒有一種方法可以遍歷2D數組以進行比較,以比較任何索引的name屬性包含的值與用戶輸入String的值相同,還是我要尋找一種完全不同的解決方案? 任何和所有幫助非常感謝。 如果格式化不正確,也表示歉意。 第一篇文章。
當前Move方法的目標是網格上Champion的實際坐標
private static void moveCharacter()
{
System.out.println("Enter Co-ords of Champ to Move");
int posx = sc.nextInt();
int posy = sc.nextInt();
if(grid[posx][posy]!=null)
{
String moving = grid[posx][posy].getName();
System.out.println("Enter Target Coordinates");
int tarx = sc.nextInt();
int tary = sc.nextInt();
if(grid[tarx][tary]==null)
{
grid[posx][posy]=null;
Champion champ = new Champion(moving, tarx, tary);
grid[tarx][tary]=champ;
printgrid();
double distance = calculateDistance(posx, posy, tarx, tary);
System.out.println("Distace Travelled " + distance);
}//End if
}//End If Pos Null
else
System.out.println("Target Position is Empty");
{
moveCharacter();
}//End Else
}//End Move Character
在玩類似的東西
String ChampToMove = "Brian";
for(int i = 0; i<grid.length; i++)
{
for(int j = 0; j<grid[i].length;j++)
{
if(grid[i][j].getName.equals(ChampToMove))
{
moveCharacter(ChampToMove );
}
}//End Nested For
最后一部分不是我目前正在使用的東西,而是我之前正在玩的東西,它只是我一直認為可以起作用的一般要點,但是我覺得它效率不高。
與您當前的算法(運行時間為O(n ^ 2))相比,我建議使用binarySearch,它的運行時間為O(nlog(n))。
一種可能的實現方式是:
for(int i = 0; i<grid.length; i++)
{
if(binarySearch(grid[i], ChampToMove))
{
moveCharacter(ChampToMove );
break;
}
}//End Nested For
和binarySearch算法:
public static boolean binarySearch(String[] a, String x) {
int low = 0;
int high = a.length - 1;
int mid;
while (low <= high) {
mid = (low + high) / 2;
System.out.println(a[mid]);
if (a[mid].compareTo(x) < 0) {
low = mid + 1;
} else if (a[mid].compareTo(x) > 0) {
high = mid - 1;
} else {
return true;
}
}
return false;
}
如果您對此有任何疑問,請問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.