简体   繁体   English

打印出乘法表

[英]Printing out a multiplication table

I'm going through the Java Tutorial on HackerRank using Java 8. The goal is to print out a multiplication table of 2 from 1 - 10. 我正在使用Java 8进行HackerRank上的Java教程。目标是从1-10打印出2的乘法表。

Here is what I came up with 这是我想出的

public static void main(String[] args) {

    int x = 2;
    int y = 0;
    int z;

    while (y < 10) {

        z = x * y;
        y++;

        System.out.println(x + " x " + y + " = " + z); 
    }

Here is the output I get from the code above 这是我从上面的代码中获得的输出

  • 2 x 1 = 0 2 x 1 = 0
  • 2 x 2 = 2 2 x 2 = 2
  • 2 x 3 = 4 2 x 3 = 4
  • 2 x 4 = 6 2 x 4 = 6
  • 2 x 5 = 8 2 x 5 = 8
  • 2 x 6 = 10 2 x 6 = 10
  • 2 x 7 = 12 2 x 7 = 12
  • 2 x 8 = 14 2 x 8 = 14
  • 2 x 9 = 16 2 x 9 = 16
  • 2 x 10 = 18 2 x 10 = 18

I've also tried while <= 10 instead of while < 10 as shown in my code above and for that my result was: 我也尝试了<= 10而不是while <10,如上面的代码所示,结果是:

  • 2 x 1 = 0 2 x 1 = 0
  • 2 x 2 = 2 2 x 2 = 2
  • 2 x 3 = 4 2 x 3 = 4
  • 2 x 4 = 6 2 x 4 = 6
  • 2 x 5 = 8 2 x 5 = 8
  • 2 x 6 = 10 2 x 6 = 10
  • 2 x 7 = 12 2 x 7 = 12
  • 2 x 8 = 14 2 x 8 = 14
  • 2 x 9 = 16 2 x 9 = 16
  • 2 x 10 = 18 2 x 10 = 18
  • 2 x 11 = 20 2 x 11 = 20

Neither of this outputs is what I'm looking for. 这些输出都不是我想要的。 Logically I am confident my code makes sense and should work so I'm looking for someone to give me tips as to something I may have missed or maybe I've made a mistake and I'm not aware of it. 从逻辑上讲,我相信我的代码有意义并且可以正常工作,因此我正在寻找可以给我一些技巧的提示,以提醒我可能遗漏的东西或者我犯了一个错误而我却不知道。 I am not looking for the code to the right answer, but rather advice and/or pointers which will allow to come up with a working solution on my own. 我不是在寻找正确答案的代码,而是在寻求建议和/或指示,这将允许我自己提出一个可行的解决方案。

  1. Start your y value at 1 y的值从1开始
  2. Don't increment your y value until after the print statement 直到打印语句后才增加y值

     public static void main(String[] args) { int x = 2; int y = 1; //starts at 1 int z; while (y < 10) { z = x * y; System.out.println(x + " x " + y + " = " + z); y++; // increment y after the print statement } } 

分配y = 1的值,并在system.out.println()之后增加它。

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

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