题干要求:
Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input
-1000000 9
Sample Output
-999,991解法一:
利用printf方法
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
scanner.close();
int sum = a + b;
if(sum < 0) {
System.out.print("-");
sum = 0 - sum;
}
if(sum >= 1000000) {
System.out.printf("%d,%03d,%03d",sum/1000000,sum%1000000/1000,sum%1000);
}else if(sum >= 1000) {
System.out.printf("%d,%03d", sum/1000,sum%1000);
}else {
System.out.println(sum);
}
}
}解法二:利用Java提供的强大的字符串处理API,两种解法都比较便捷
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
scanner.close();
int sum = a + b;
if(sum < 0) {
System.out.print("-");
sum = 0 - sum;
}
String sumStr = String.valueOf(sum);
int length = sumStr.length();
StringBuffer stringBuffer;
if(length <= 3) {
System.out.println(sumStr);
} else if(length <= 6) {
stringBuffer = new StringBuffer(sumStr);
stringBuffer.insert(length - 3, ",");
System.out.println(stringBuffer.toString());
} else {
stringBuffer = new StringBuffer(sumStr);
stringBuffer.insert(length - 3, ",");
stringBuffer.insert(length - 6, ",");
System.out.println(stringBuffer.toString());
}
}
}
本文介绍了一种使用Java程序解决特定格式输出问题的方法。输入为两个整数a和b,输出其和,并按标准格式显示结果,即用逗号分隔每三位数字。提供了两种解决方案,一种是使用printf进行格式化输出,另一种是利用Java字符串处理API实现。
1万+

被折叠的 条评论
为什么被折叠?



