晚上好,我在課堂作業方面遇到了麻煩(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]
如何格式化我的答案,使其看起來像示例中的答案?
uj5u.com熱心網友回復:
不使用 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 " ");
}
uj5u.com熱心網友回復:
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 " ");
}
}
}
uj5u.com熱心網友回復:
for(int i = 1; i <= N ^ 2; i^2) {
System.out.printf("%d ", i);
}
應該測驗...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427739.html
