简体   繁体   English

使用Java循环制作时间表

[英]Using Java for loops to make a times table

I'm trying to make a Java program that creates multiplication tables using nested for loops by asking the user for upper bounds and display the following result such as this (first image attached). 我试图制作一个Java程序,通过向用户询问上限并使用嵌套的for循环来创建乘法表,并显示如下结果(如上图所示)。 Desired format 所需格式

However, my code is causing it the program to only print out the multiple of the two inputs and looping that the same amount of times as the multiple. 但是,我的代码使程序仅输出两个输入的倍数,并以与倍数相同的次数循环。 For example in here (second image attached), if it put in the input as 3 and 5, it is displaying 15 to me 15 times. 例如,在这里(附有第二张图片),如果将输入内容分别设为3和5,则会向我显示15次15次。 My displayed format 我显示的格式

This is what my code looks like (last image attached): 这是我的代码的样子(附上最后一张图片):

My code 我的密码

Thank you all so much in advance. 提前谢谢大家。 Please help me out!!! 请帮帮我!!! I've been stuck on this for a while. 我已经坚持了一段时间。

Try this: 尝试这个:

public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int firstFactor = 0;
        int secondFactor = 0;
        System.out.print("Enter the first factor: ");
        firstFactor = s.nextInt();
        System.out.print("Enter the second factor: ");
        secondFactor = s.nextInt();
        for(int i=1; i<=firstFactor; i++) {
            for(int j=1; j<=secondFactor; j++) {
                System.out.println(i + " * " + j + " = " + i*j);
            }
            System.out.println();
        }
    }

Output: 输出:

Enter the first factor: 3
Enter the second factor: 5
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15

Modifications: 修改:

  1. Change firstFactor*secondFactor to i*j . firstFactor*secondFactor更改为i*j Since firstFactor was 3 and secondFactor was 5 . 由于firstFactor was 3secondFactor was 5 Hence you were getting 15 as an output each time. 因此,您每次获得15作为输出。

I would strongly suggest not using an image for your code. 我强烈建议您不要在代码中使用图片。 You can just add it as part of your question using the provided edit tools (or Ctrl+k). 您可以使用提供的编辑工具(或Ctrl + k)将其添加为问题的一部分。 Anyway, from a quick look your code looks fine with one bug. 无论如何,从快速的外观来看,您的代码看起来只有一个错误。 You just need to do this: 您只需要这样做:

System.out.println(i*j)

Where you had: 您在哪里:

System.out.println(firstFactor*secondFactor)

Those are set to input values and do not change during the loop. 这些设置为输入值,并且在循环期间不会更改。

Change your first and second factor to i and j. 将第一个和第二个因子更改为i和j。

for(int i=1;i<=3;i++) {
        for(int j=1; j<=5; j++) {
            System.out.print("i: "+i+" j: "+j);
            System.out.println(" Value: "+i*j);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM