英文:
Is it possible to print a char in between Multi-Dimensional Array in Java?
问题
我正在学习使用Java编程,我想要创建多维数组,其中我希望它打印两个数字和一个字符在中间,这样我可以为我的儿子生成随机的数学乘法问题进行练习。
到目前为止,我已经完成了这个任务,但是'x'也会打印在末尾。我只想打印随机的两个数字,然后输出为 (1 x 2 = )。
这是我目前的代码:
package exercises;
public class TimeTable {
public static void main(String[] args) {
int[][] nums = new int[10][2];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
nums[i][j] = (int) (Math.random() * 10);
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(nums[i][j] + " x ");
}
System.out.println("=");
}
}
}
运行时,它会打印如下内容:
7 x 1 x =
9 x 9 x =
6 x 3 x =
0 x 6 x =
0 x 2 x =
0 x 4 x =
0 x 8 x =
8 x 5 x =
8 x 8 x =
8 x 3 x =
我不希望在等号前打印最后的'x'。
谢谢大家。
我尝试只打印等号,但这会导致混淆。我还尝试打印数组的第一行,然后使用另一个单独的函数打印数组的最后一部分,带有'+',但这没有起作用,反而引发了一个大错误。
英文:
I am still learning to code in Java and I want to build Multi-Dimensional arrays where I want it to print two numbers and a char in between so I can randomize maths multipication questions for my son to exercise.
So far I have managed to get it done but 'x' is also printing at the end. All I want to print is randoming two numbers and printing as ( 1 x 2 = ).
This is what I have so far :
package exercises;
public class TimeTable {
public static void main(String[] args) {
int[][] nums = new int[10][2];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
nums[i][j] = (int) (Math.random() * 10);
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(nums[i][j] + " x ");
}
System.out.println("=");
}
}
}
and it prints the following when I run it:
7 x 1 x =
9 x 9 x =
6 x 3 x =
0 x 6 x =
0 x 2 x =
0 x 4 x =
0 x 8 x =
8 x 5 x =
8 x 8 x =
8 x 3 x =
I do not want the last 'x' before the equal sign.
Thank you all.
I tried to print the equal sign only and it was confusing. I tried to print first line of the array and then another seperate function to print the last bit of the array with '+' and it didnt worked instead it throw and huge error.
答案1
得分: 2
你可以这样做
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(nums[i][j]);
if(j == 0)
System.out.print(" x ");
}
System.out.println("=");
}
英文:
You could do it this way
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(nums[i][j]);
if(j == 0)
System.out.print(" x ");
}
System.out.println("=");
}
答案2
得分: 2
for (int i = 0; i < 10; i++) {
System.out.println(nums[i][0] + " x " + nums[i][1] + " = ");
}
英文:
for (int i = 0; i < 10; i++) {
System.out.println(nums[i][0] + " x "+nums[i][1]+" = ");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论