java - 如何使用表中的 if 函数在循环中排列重复字符串数组
问题描述
我想将随机输入字符串数组排列到表中,使用循环和 if 函数或更简单的方法。
有最小的、小的、中的、大的和最大的。并且每个字符串都是重复的 x5
数组是:
String cow[][] = new String[5][5];
cow[0][0] = "big";
cow[0][1] = "smallest";
cow[0][2] = "small";
cow[0][3] = "medium";
cow[0][4] = "biggest";
cow[1][0] = "smallest";
cow[1][1] = "biggest";
cow[1][2] = "medium";
cow[1][3] = "small";
cow[1][4] = "big";
cow[2][0] = "medium";
cow[2][1] = "biggest";
cow[2][2] = "big";
cow[2][3] = "smallest";
cow[2][4] = "small";
cow[3][0] = "small";
cow[3][1] = "big";
cow[3][2] = "smallest";
cow[3][3] = "medium";
cow[3][4] = "biggest";
cow[4][0] = "biggest";
cow[4][1] = "medium";
cow[4][2] = "big";
cow[4][3] = "small";
cow[4][4] = "smallest";
我的排列数组的代码:
for (int j = 0; j < cow.length; j++) {
for (int i = 0; i < cow[j].length; i++) {
if (cow[i][j] == "smallest") {
System.out.print("| " + cow[i][j] + " |");
} else if (cow[i][j] == "small") {
System.out.print("| " + cow[i][j] + " |");
} else if (cow[i][j] == "medium") {
System.out.print("| " + cow[i][j] + " |");
} else if (cow[i][j] == "big") {
System.out.print("| " + cow[i][j] + " |");
} else if (cow[i][j] == "biggest") {
System.out.print("| " + cow[i][j] + " |");
}
}
System.out.println();
}
当我运行代码时,我只得到
最小 |
最小 |
最小 |
最小 |
最小 |
我认为这是因为循环没有为其他索引重新循环(?),所以表不是 5x5
我所期望的:
smallest | small | medium | big | biggest
smallest | small | medium | big | biggest
smallest | small | medium | big | biggest
smallest | small | medium | big | biggest
smallest | small | medium | big | biggest
请教我,因为我对java很陌生。谢谢
解决方案
您需要使用 equals 方法比较两个字符串。
if ((cow[i][j]).equals("small")) {
........ }
推荐阅读
- c# - CsvHelper - How to map by index the whole row to a model member
- c# - How does Package Manager Console know which connection string to use?
- javascript - VSCode jsconfig and intellisense
- c# - Video stream from webcam and Sending through websocket and saving into mp4
- python - How to make a clear messages command in cog
- go - can you use a primitive or inbuild data types as a method in golang
- sql - Join two tables, get all results from first table
- python - 使用 BeautifulSoup 选择下拉框值时无法抓取数据
- python - Create a Python executable with Selenium webdriver manager
- flutter - 如何遍历所有文档?(火库)