PAT class B 1002 write this number (Java)

Keywords: less REST Java

The topics are as follows:

Read in a positive integer n, calculate the sum of its digits, and write each digit of the sum in Chinese pinyin.

Input format:

Each test input contains one test case, that is, it gives the value of natural number n. It is guaranteed that n is less than 10 100.

Output format:

For each digit of the sum of the digits output in a line, there is a space between the Pinyin digits, but there is no space after the last Pinyin digit in a line.

Input example:

1234567890987654321123456789

Output example:

 

yi san wu

To calculate the sum of each digit, first think of inputting such a string of digits with a string, and then convert it into an array of characters to sum. For Pinyin output, space should be considered. When the variable j is equal to the length of the array, no spaces are output, and spaces are output for the rest of the time.

The complete code is as follows:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
	Scanner in = new Scanner(System.in);
	String n = in.nextLine();
	char[] a = n.toCharArray();
	in.close();
	int sum=0;
	for(int i=0;i<=a.length-1;i++) {
		sum=sum+a[i]-48;
	}
String s=Integer.toString(sum);
char[]b=s.toCharArray();
for(int j=0;j<=b.length-1;j++) {
	if(j==b.length-1) {
		if(b[j]=='0') {
			System.out.print("ling");
		}
		if(b[j]=='1') {
			System.out.print("yi");
		}
		if(b[j]=='2') {
			System.out.print("er");
		}
		if(b[j]=='3') {
			System.out.print("san");
		}
		if(b[j]=='4') {
			System.out.print("si");
		}
		if(b[j]=='5') {
			System.out.print("wu");
		}
		if(b[j]=='6') {
			System.out.print("liu");
		}
		if(b[j]=='7') {
			System.out.print("qi");
		}
		if(b[j]=='8') {
			System.out.print("ba");
		}
		if(b[j]=='9') {
			System.out.print("jiu");
		}
	}else {
	if(b[j]=='0') {
		System.out.print("ling"+" ");
	}
	if(b[j]=='1') {
		System.out.print("yi"+" ");
	}
	if(b[j]=='2') {
		System.out.print("er"+" ");
	}
	if(b[j]=='3') {
		System.out.print("san"+" ");
	}
	if(b[j]=='4') {
		System.out.print("si"+" ");
	}
	if(b[j]=='5') {
		System.out.print("wu"+" ");
	}
	if(b[j]=='6') {
		System.out.print("liu"+" ");
	}
	if(b[j]=='7') {
		System.out.print("qi"+" ");
	}
	if(b[j]=='8') {
		System.out.print("ba"+" ");
	}
	if(b[j]=='9') {
		System.out.print("jiu"+" ");
	}}
}
}
}

After that, I inquired about other people's practices, which was much simpler. You can use an array of pinYin to store the pinYin of 0-9, and then use System.out.print(pinYin[sumString.charAt(i) - 48]); to directly take down the output result.

Links: https://blog.csdn.net/coder__666/article/details/80213319

Posted by jaronblake on Sun, 24 Nov 2019 09:59:48 -0800