double total = 0;
while(in.hasNextDouble()){
double value = in.nextDouble();
out.printf("%15.2f\n", value);
total = total + value;
}
out.printf("Total: %8.2f\n", total);
我尝试修改的代码的简短片段。它目前逐行输出输入文件中的所有内容。
double total = 0;
int count = 0;
while(in.hasNextDouble()){
if(count == 0){
double value = in.nextDouble();
out.printf("%4.2f", value);
count = 1;
total = total + value;
}
else if(count == 1){
double value = in.nextDouble();
out.printf("%15.2f\n", value);
count = 0;
total = total + value;
}
}
if(count == 1){
out.print("\n");
}
out.printf("Total: %8.2f\n", total);
我以这种方式修改它并且它有效,但我觉得它真的很长。我缺少一种较短的方法吗?
答案 0 :(得分:0)
有很多方法可以做到这一点。一种方式:
double total = 0;
while(in.hasNextDouble()){
double value = in.nextDouble();
out.printf("%4.2f", value);
total += value;
if ( in.hasNextDouble() {
double value = in.nextDouble();
out.printf("%15.2f", value);
total += value;
} else {
out.print("\n");
break;
}
out.print("\n");
}
out.printf("\nTotal: %8.2f\n", total);