我的任务是制作1-10的乘法表,但我对我的代码不满意,似乎很长:
for (int i = 1; i <= 10; i++)
{
System.out.println("1x" + i + " = " + i + "\t" + "2x" + i + " = " + (2*i)
+ "\t" + "3x" + i + " = " + (3*i) + "\t" + "4x" + i + " = " + (4*i)
+ "\t" + "5x" + i + " = " + (5*i) + "\t" + "6x" + i + " = " + (6*i)
+ "\t" + "7x" + i + " = " + (7*i) + "\t" + "8x" + i + " = " + (8*i)
+ "\t" + "9x" + i + " = " + (9*i) + "\t" + "10x" + i + " = " + (10*i));
}
输出:
1x1 = 1 2x1 = 2
1x2 = 2 2x2 = 4
etc.
答案 0 :(得分:7)
尝试类似
的内容for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.println(i + "x" + j + "=" (i*j));
}
}
所以你有一个内循环和一个外循环,控制你想要的乘法和你希望它乘以乘以。
为了更明确,您可以(应该?)将i
和j
重命名为multiplier
和multiplicand
答案 1 :(得分:3)
这将格式化表格,如何在示例代码中使用它,并使用两个循环:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print(i + "x" + j + "=" + (i * j) + "\t");
}
System.out.println();
}
外部循环控制乘法表中的行,内部循环控制乘法表中的列。 System.out.println()表示移动到表的新行
答案 2 :(得分:1)
你可以使用两个循环:
for (int i = 1; i <= 10; i++)
{
for (int j = i; j <= 10; j++)
{
System.out.println(i + "x" + j + "=" + (i*j));
}
}
答案 3 :(得分:1)
for (int i = 1; i <= 10; i++)
{
for(int j=1; j<10; j++){
System.out.println(j+"x"+i+"="+(j*i)+"\t");
}
System.out.println("\n");
}
答案 4 :(得分:0)
import java.util.Scanner;
public class TableMultiplication {
public static void main(String[] args) {
int table,count,total;
//Reading user data from console
Scanner sc = new Scanner(System.in);
//reading data for table
System.out.println("Enter Your Table:");
table = sc.nextInt();
//reading input for how much want to count
System.out.println("Enter Your Count to Table:");
count = sc.nextInt();
//iterate upto the user required to count and multiplay the table and store in the total and finally display
for (int i = 1; i < count; i++) {
total = table*i;
System.out.println(table+"*"+i+"="+total);
}//for
}//main
}//TableMultiplication
答案 5 :(得分:-2)
import java.util.Scanner;
public class P11 {
public static void main(String[] args) {
Scanner s1=new Scanner(System.in);
System.out.println("Enter a value :");
int n=s1.nextInt();
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
{
System.out.println(i+"x"+j+ "="+(i*j)+"\t");
}
}
}
}