作为初学者和java,我的代码输出有问题。代码仅为运行代码时输入的值打印“a”,“b”和“c”的值。我如何修改它以打印所有值,包括我在运行代码时所使用的值 有人可以帮忙吗?谢谢!
class Numbers
{
public static void main (String[] args)
{
for ( int i = 0; i < args.length; i++)
{
int a = Integer.parseInt(args[i]);
System.out.print(a);
int b = (a*a);
int c = (a*a*a);
System.out.print(b);
System.out.print(c);
}
}
}
答案 0 :(得分:0)
循环只运行一次,因为你的参数是3.所以args.length
是1.这就是打印3,9和27的原因。
要使循环运行三次,您可以将String
作为args[0]
评估为int
。在这种情况下,你需要类似的东西(这里没有异常处理):
int numLoops = Integer.parseInt(args[0]);
for ( int i = 0; i < numLoops; i++)
System.out.print(i);
System.out.print(i*i);
System.out.println(i*i*i);
}
答案 1 :(得分:0)
So did I get it right in your comment? You want to pass a number that tells you how many iterations the loop should run. And for any iteration you want to write a incrementing number, its square and its cube?
class Numbers {
public static void main (String[] args) {
if (args.length == 0) {
System.out.println("Please specify number.");
return;
}
int iterationCount = Integer.parseInt(args[0]);
for ( int i = 0; i < iterationCount; i++) {
int a = i;
System.out.print(a);
int b = (a*a);
int c = (a*a*a);
System.out.print(b);
System.out.print(c);
}
}
}
答案 2 :(得分:0)
Please try this
javac Numbers.java
java Numbers 1 2 3
This should work. In first iteration of your for loop, the a variable will be 1, so it will print 1, 1 and 1. In second iteration, your a variable will be 2, so it will print 2, 4 and 8 and in your third iteration, your a variable will be 3, so it will print 3, 9 and 27.