if 和while的混用...

本文介绍了一个使用Java递归填充并打印二维数组的方法。通过正确的条件判断与循环使用,实现了特定模式的数字填充,并利用printf函数进行了数字格式化输出。
关于打印出
1 2 9 10 25 26 49 50 81 82
4 3 8 11 24 27 48 51 80 83
5 6 7 12 23 28 47 52 79 84
16 15 14 13 22 29 46 53 78 85
17 18 19 20 21 30 45 54 77 86
36 35 34 33 32 31 44 55 76 87
37 38 39 40 41 42 43 56 75 88
64 63 62 61 60 59 58 57 74 89
65 66 67 68 69 70 71 72 73 90
100 99 98 97 96 95 94 93 92 91
的数组。

一直保持循环的思维,错将if用while来代替,运行了半天也没发现原因...幸好虹哥帮指正了,还有数字的格式输出。正确代码如下~


public class PrintArray {

static void initial(int[][] a, int n) {
if (n > 0) {
if (n % 2 == 0) {
int temp = (n - 1) * (n - 1) + 1;
for (int i = 0; i < n; i++) {
a[i][n - 1] = temp++;
}
for (int j = n - 2; j >= 0; j--) {
a[n - 1][j] = temp++;
}
initial(a ,n - 1);
} else {
int temp = (n - 1) * (n - 1) + 1;
for (int i = 0; i < n; i++) {
a[n - 1][i] = temp++;
}
for (int j = n - 2; j >= 0; j--) {
a[j][n - 1] = temp++;
}
initial(a ,n - 1);
}
}
}

static void print(int[][] a, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%03d", a[i][j]);//System.out.printf("%3d", a[i][j])
System.out.print(" ");
}
System.out.println("");
}
}

public static void main(String[] args) {
int n=10;
int [][] a=new int[n][n];
initial(a,n);
print (a,a.length);
}
}
在实现文件拷贝功能的 Java 程序里,`scanner.nextLine()` 方法主要用于从控制台读取用户输入的一行文本。 在文件拷贝程序中,使用 `scanner.nextLine()` 可以让用户输入源文件名目标文件名。示例代码如下: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; public class FileCopy { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入源文件名: "); String sourceFileName = scanner.nextLine(); File sourceFile = new File(sourceFileName); if (!sourceFile.exists()) { System.out.println("源文件不存在,请检查文件名。"); return; } System.out.print("请输入目标文件名: "); String targetFileName = scanner.nextLine(); try (FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetFileName)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } System.out.println("文件拷贝成功!"); } catch (IOException e) { System.out.println("文件拷贝过程中出现错误: " + e.getMessage()); } } } ``` 在上述代码中,`scanner.nextLine()` 被用来接收用户输入的源文件名目标文件名。每次调用 `scanner.nextLine()` 时,程序会等待用户输入一行文本,按下回车键后,这行文本就会被读取并赋值给相应的变量。 需要注意的是,在处理输入的时候,尽量只使用 `Scanner` 的 `nextLine()` 方法接收输入,不要将 `nextLine()` 与其它 `next` 方法混用,否则可能会出现行尾回车换行未处理影响下次输入的情况。若有需要通过控制台输入 `int`,可以先输入 `String` 然后再通过 `parseInt` 等将 `String` 转成 `int` [^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值