英文:
I need to detect forms in ArrayList
问题
public static void main(String[] args) throws IOException {
ArrayList<String> cajita = new ArrayList<String>();
Scanner entrada = new Scanner(System.in);
System.out.println("请输入第一行4位数字。\n如果是塑料块,请输入'x'。\n如果不是,请输入'.'。\n最多4个字符!");
for (int i = 0; i < 4; i++) {
cajita.add(entrada.nextLine());
}
boolean isPlasticCube = true;
for (int i = 0; i < 4; i++) {
for (int f = 0; f < 4; f++) {
if (cajita.get(i).charAt(f) != 'x') {
isPlasticCube = false;
break;
}
}
if (!isPlasticCube) {
break;
}
}
if (isPlasticCube) {
System.out.println("是一个块");
} else {
System.out.println("不是一个块");
}
}
英文:
Hi my problem is that i have to implement a logic that detect if for example the "X" makes a 2x2 square. In this code you have to insert 4 times a string of 4 digits in an ArrayList in which it will be a "X" if its a a "plastic cube" ("plastic cube" helps to visualize that the output is a "plastic form") or a "." if its not.
So if the input is:
..XX
..XX
....
....
I have to detect that is a cube 2X2 and return for example "Its a cube".
I would appreciate if you could help me since I am stuck.
public static void main(String[] args)throws IOException { {
ArrayList <String> cajita=new <String> ArrayList();
Scanner entrada=new Scanner(System.in);
System.out.println("Enter the first 4-digit line."
+ " \nIt should contain 'x' if it is a piece of plastic."
+ " \nY '.' in other case."
+ " \n Max 4 chars!");
for(int i=0;i<4;i++) {
cajita.add(entrada.nextLine());
}
for(int i=0;i<4;i++) {
System.out.println();
for(int f=0;f<4;f++) {
System.out.print(cajita.get(i).charAt(f));
}
}
}
}
答案1
得分: 0
你可以像这样做:
-
验证用户输入的行是否恰好为4个字符长,并且仅包含
。
和X
,否则请用户重新输入有效的行。 -
一旦你有了4行有效数据,就计算X的数量。如果不是4个,那么它不是一个正方形。
-
找到第一个X,然后:
-
检查该行中下一个位置是否也是X。
-
检查下面一行是否在相同位置有X。
-
检查下面一行是否在下一个位置有X。
-
-
如果其中任何一项检查失败,那么它不是一个正方形。
-
否则它是一个正方形。
祝你编码愉快。
英文:
You can do it like this:
-
Verify that a user-entered line is exactly 4 long and consists of only
.
andX
, otherwise ask user to re-enter a valid line. -
Once you have 4 valid lines, count the number of X's. If not 4, then it's not a square.
-
Find the first X, then:
-
Check that next position in the line is also an X.
-
Check that line below has X in same position.
-
Check that line below has X in next position.
-
-
If any of those checks fail, then it's not a square.
-
Otherwise it's a square.
Have fun coding that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论