2016-11-14 20 views
0

我有一个for循环,调用它的方法是printMe(),我希望用户能够确定它的输入运行次数。这是一起什么,我想这应该是线路:如何让循环运行的次数与用户输入一样多?

System.out.println("Enter a number: "); 
    loop = input.nextInt(); 
+0

你得到它的工作? – ItamarG3

+0

嗨Itamar Green,当我试图整合你的代码时,我找不到输入符号。 –

+0

Scanner对象的名称需要与用于调用'.nextInt()'的名称相同。 – ItamarG3

回答

2

这应该工作:

Scanner input = new Scanner(System.in); 
int loop = input.nextInt(); 
for(int i = 0; i<loop;i++){ 
    //do the thing 
} 
2

用户输入感谢阅读到扫描仪

Scanner sc = new Scanner(System.in); 
int loopNum = sc.nextInt(); 
for (int i=); i<loopNum; i++){ 
    printMe(); 
} 
1

应该是这样的:

for (int i=0; i<loopNum; i++) 
    printMe(); 

干杯

1

是的,如果您的变量输入来自Scanner。你可以像这样声明变量sc,并且如果你想阅读更多的用户输入,可以多次调用它。

Scanner sc = new Scanner(System.in); 
System.out.println("Enter a number: "); 
loopNum = sc.nextInt(); 
相关问题