I wrote this in Java, and I want the output such that it creates a space after every value except for the last one. How do I get it to show up like 1[]2[]3[]4[]5[]6[]7
rather than 1[]2[]3[]4[]5[]6[]7[]
?
Here is my code!
public class Pentagonal {
public static void main(String[] args) {
int n, x, n1;
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
n = input.nextInt();
n1 = 1;
System.out.print("The pentagonal numbers are: ");
while (n1 <= n) {
x = (3 * n1 * n1 - n1) / 2;
if (n1 == n)
System.out.print(x);
else
System.out.print(x + " ");
n1++;
}
}
}
Your code is perfectly fine. I see no problem with it. Just check this out
while (n1 <= n) {
x = (3 * n1 * n1 - n1) / 2;
System.out.print(x + ((n1 == n) ? "\n" : " "));
n1++;
}
Replace this "\\n"
(new line) with " "
(space) if you want!
只需在while循环后添加以下行
System.out.print("\b");
Try:
if(n1==n)
System.out.print(x);
else
if(n1 != n-1) {
System.out.print(x+" ");
} else {
System.out.print(x);
}
n1++;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.