我需要编写一个名为
printOnLines()
的方法,它接受两个参数:一个整数 n 和一个 inLine 整数,并在一行上的每个 inLine
上打印 n 个整数。
for n = 10, inLine = 3:
1, 2, 3
4, 5, 6
7, 8, 9
10
我的电话是
(10,3)
。这是我的代码:
public static void printOnLines(int n, int s) {
for(int i=1; i<=s; i++) {
for(int j=1; j<=n-1; j++) {
System.out.print(j + ", ");
}
System.out.println();
}
}
}
我认为有两个错误:
使用这个:
public static void printOnLines(int n, int s){
StringBuilder builder = new StringBuilder();
for(int i = 1; i <= n; i++){
builder.append(i);
if(i % s == 0)builder.append("\n");
else builder.append(", ");
}
System.out.println(builder.toString().substring(0,builder.toString().length() - 2));
}
我想你已经必须提交作业了,所以我会这样做:
class printonlines {
public static void main(String[] args) {
printOnLines(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
public static void printOnLines(int n, int s) {
for(int i=1; i<=n; i++) { // do this loop n times
if ( (i != 1) && (i-1)%s == 0 ) { // if i is exactly divisible by s, but not the first time
System.out.println(); // print a new line
}
System.out.print(i);
if (i != n) { // don't print the comma on the last one
System.out.print(", ");
}
}
}
}
哦,你不想使用任何
if
语句。你真正从做“技巧”(比如你被要求做的事情)中学到的只是一个技巧,而不是如何编写易于理解的代码(即使你稍后必须调试)代码。
无论如何,这是我不太容易理解但更棘手的代码,根据 @DavidWallace 的答案的建议,它没有使用
if
。我确信有人可以做得更简洁,但这是我在 15 分钟内能做的最好的......
class printonlineswithnoifs {
public static void main(String[] args) {
printOnLines(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
}
// i 012012012
// j 000333666
// i+j 012345678
public static void printOnLines(int n, int s) {
int i = 0;
int j = 1;
for (; j <= n; j+=s) {
for (; i < (s-1) && (j+i)<n; i++) {
System.out.print((i+j) + ", ");
}
System.out.println(i+j);
i=0;
}
}
}
我不会发布完整的解决方案,因为这显然是家庭作业。但如果不允许我使用
if
语句或三元运算符,这就是我会做的。
s
,而不是 1(因此在您的示例中为 0、3、6、9)。编辑
好的,根据@localhost的要求,这是我的解决方案。
public static void printOnLines(int n, int s) {
for (int i = 0; i < n; i += s) {
int j;
for (j = 1; j < s && i + j < n; j++) {
System.out.print(i + j + ", ");
}
System.out.println(i + j);
}
}
这是您想要的代码示例..
public static void printOnLines(int n, int s) {
for (int i = 1; i < n; i++) {
System.out.print(i + ",\t");
if (i % 3 == 0) System.out.println();
}
System.out.println(n);
}