Java实现将两个数之和用标准形式输出

程序目的是将形如-23455066,2345539转化成-23,455,066,2,345,539形式。

程序中用到的主要方法是String的toCharArray()方法,该方法将字符串转化成字符数组,获取到数组后就可以利用其进行修改,完整代码如下:


package testcode;

import java.util.Scanner;

public class PAT1001 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scanner=new Scanner(System.in);
		int a=Integer.parseInt(scanner.next());
		int b=Integer.parseInt(scanner.next());
		Integer c=a+b;
		String s =  c.toString();
		char[] strings2 = s.toCharArray();
		int num;
		char[] output;
		int i=0,k;
		if (strings2[0]=='-') {
			if ((strings2.length-1)%3==0) {
				num=(strings2.length-4)/3;
			}else {
				num=(strings2.length-1)/3;
			}
		
		    output=new char[strings2.length+num];
			i=0;
			k=output.length;
			for (int j = strings2.length-1; j >=0 ; j--) {
				i++;
				k--;
				if (i%3==0&&k>=2) {
					output[k]=strings2[j];
					k--;
					if(k>=0){
					output[k]=',';
					}
				}else{
					output[k]=strings2[j];
				}
			}
		}else{
			if (strings2.length%3==0) {
				num=(strings2.length-3)/3;
			}else {
				num=strings2.length/3;
			}
			
			output=new char[strings2.length+num];
			i=0;
			k=output.length;
			for (int j = strings2.length-1; j >= 0; j--) {
				i++;
				k--;
				output[k]=strings2[j];
				
				if(i%3==0){
					k--;
					if(k>=0){
					output[k]=',';
					}
				}
			}
		}
		
		System.out.println(output); 
	}

}


你可能感兴趣的:(java,Scanner,tochararray)