英文:
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("---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++)
num = num*x;
System.out.print(+num+ ", ");
}
}
答案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 <= multiples; x++) {
num = num * x;
System.out.print(num + ", ");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论