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

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

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

问题

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("---Multiples---\n");

    System.out.print("Enter a number: ");
    int num = keyboard.nextInt();
    System.out.print("Enter the number of multiples you would like to see for the number " + num + " :");
    int multiples = keyboard.nextInt();

    System.out.print("\nThe first " + multiples + " multiples of " + num + " are: ");

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

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:

import java.util.Scanner;
public class Main
{
  public static void main(String[] args)
  {
    Scanner keyboard = new Scanner(System.in);
    System.out.println(&quot;---Multiples---\n&quot;);
    
    System.out.print(&quot;Enter a number: &quot;);
    int num = keyboard.nextInt();
    System.out.print(&quot;Enter the number of multiples you would like to see for the number &quot;+num+&quot; :&quot;);
    int multiples = keyboard.nextInt();
    
    System.out.print(&quot;\nThe first &quot;+multiples+&quot; multiples of &quot;+num+&quot; are: &quot;);
    
    for(int x=1;x==multiples;x++)
    num = num*x;
    System.out.print(+num+ &quot;, &quot;);
  }
}

答案1

得分: 1

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

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

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

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

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:

确定