java :避免为输出的最后一行打印新行



我正在打印文件中长数字之间的差异,并在循环中列出结果。但我不想打印最后一个结果的换行符。

下面是打印结果的代码:

public static void main(String[] args) {
Scanner sc;
long a = 0, b = 0;
try {
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
String split[] = line.split("\s+");
a = Long.parseLong(split[0]);
b = Long.parseLong(split[1]);
System.out.println(Math.abs(a-b));
}
input.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}

我现在得到的输出是:

2
71293781685339
12345677654320

这最后有一个换行符。 打印上一个结果时如何避免新行?有什么想法吗?

在打印新行之前,您可以检查是否仍有输入需要处理

while (input.hasNextLine()) {
String line = input.nextLine();
String split[] = line.split("\s+");
a = Long.parseLong(split[0]);
b = Long.parseLong(split[1]);
System.out.print(Math.abs(a-b)); //Print without a newline
if (input.hasNextLine()) {
System.out.println();//Print new line if there is more input left
}
}

使用System.out.println(line)打印第一行,并使用System.out.print("n" + line)打印其余行。

最新更新