如何根据用户输入使循环运行X次?

huangapple go评论116阅读模式
英文:

How do I make a loop run for X amount of times from user input?

问题

  1. import java.util.Scanner;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner keyboard = new Scanner(System.in);
  5. System.out.println("---Multiples---\n");
  6. System.out.print("Enter a number: ");
  7. int num = keyboard.nextInt();
  8. System.out.print("Enter the number of multiples you would like to see for the number " + num + " :");
  9. int multiples = keyboard.nextInt();
  10. System.out.print("\nThe first " + multiples + " multiples of " + num + " are: ");
  11. for (int x = 1; x <= multiples; x++) {
  12. int multiple = num * x;
  13. System.out.print(multiple);
  14. if (x < multiples) {
  15. System.out.print(", ");
  16. }
  17. }
  18. }
  19. }
英文:

I need to build a program that asks the user for a number and how many multiples of the number they want to see. The program will then display the entered number and the first x of its multiples. How do I make a loop run for X amount of times from user input? I need to make the multiples of the user inputted number list multiples for the number of multiples the user wants. It should execute like this:

---Multiples---

Enter a number: 8
Enter the number of multiples you would like to see for the number 8 :5

The first 5 multiples of 8 are: 8, 16, 24, 32, 40

Here is My code:

  1. import java.util.Scanner;
  2. public class Main
  3. {
  4. public static void main(String[] args)
  5. {
  6. Scanner keyboard = new Scanner(System.in);
  7. System.out.println(&quot;---Multiples---\n&quot;);
  8. System.out.print(&quot;Enter a number: &quot;);
  9. int num = keyboard.nextInt();
  10. System.out.print(&quot;Enter the number of multiples you would like to see for the number &quot;+num+&quot; :&quot;);
  11. int multiples = keyboard.nextInt();
  12. System.out.print(&quot;\nThe first &quot;+multiples+&quot; multiples of &quot;+num+&quot; are: &quot;);
  13. for(int x=1;x==multiples;x++)
  14. num = num*x;
  15. System.out.print(+num+ &quot;, &quot;);
  16. }
  17. }

答案1

得分: 1

你必须修复你的循环条件,并在for循环周围加上大括号以执行多个语句。尝试这样做:

  1. for (int x = 1; x <= multiples; x++) {
  2. num = num * x;
  3. System.out.print(num + ", ");
  4. }
英文:

You have to fix your loop condition and put curly braces around your for loop to execute more than one statement. Try this:

  1. for(int x = 1; x &lt;= multiples; x++) {
  2. num = num * x;
  3. System.out.print(num + &quot;, &quot;);
  4. }

huangapple
  • 本文由 发表于 2020年10月19日 04:44:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64418182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定