如何在java中找到一系列数字的完美平方



晚上好,我在课堂作业上遇到了麻烦(java新手(:

N is read from the input, and will be an integer in the range 1 to 20. Your program should print out the squares of the numbers from 1 up to and including N, all on a single line, with one space between the numbers. You can use System.out.print() rather than System.out.println() for this.
For example, if 5 is the input, then your output would be:
1 4 9 16 25

这是我到目前为止的代码:

import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
public class Code {

static Scanner scanner = new Scanner(System.in);

public static void main(String[] args){
int N = scanner.nextInt();

// Your code here.
for(int i = 1; i <= N; i+=1) {           
int s = (i * i);
List<String>  answer = Arrays.asList(

NumberFormat.getNumberInstance(Locale.US).format(s).split(""));    
System.out.print(answer);
}
}
}

我的输出:

[1][4][9][1, 6][2, 5]

如何将我的答案格式化为与示例中的答案相似?

在不使用List 的情况下循环打印它们怎么样

for(int i = 1; i <= N; i+=1) {           
System.out.printf("%d ", i*i);
}

for(int i = 1; i <= N; i+=1) {           
System.out.print(i*i + " ");
}
public class Code {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int N = scanner.nextInt();
// Your code here.
for (int i = 1; i <= N; i += 1) {
System.out.print( i * i +" ");
}
}
}
for(int i = 1; i <= N ^ 2; i^2) {           
System.out.printf("%d ", i);
}

应该进行测试。。。

最新更新