求Java写一个类用于演示输入一个5位数,计算出各位数的总和,并倒序输出。
2个回答
展开全部
import java.*;
import java.util.Scanner;
public class Test4
{
public static void main(String[] args)
{
System.out.println("请输入一个五位数:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println("该数字各位和为"+getSum(num));
System.out.println("该数字倒序输出为"+reverse(num));
System.out.println("该数字各位和倒序输出为"+reverse2(num));
}
private static String reverse2(int num)
{
int num2 = getSum(num);
return reverse(num2);
}
private static String reverse(int num)
{
StringBuffer numstr = new StringBuffer(""+num);
numstr = numstr.reverse();
return new String(numstr);
}
public static int getSum(int num)
{
String numStr = num + "";
int sum = 0;
for (int i = 0; i < numStr.length(); i++)
{
sum = sum+numStr.charAt(i)-'0';
}
return sum;
}
}
import java.util.Scanner;
public class Test4
{
public static void main(String[] args)
{
System.out.println("请输入一个五位数:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println("该数字各位和为"+getSum(num));
System.out.println("该数字倒序输出为"+reverse(num));
System.out.println("该数字各位和倒序输出为"+reverse2(num));
}
private static String reverse2(int num)
{
int num2 = getSum(num);
return reverse(num2);
}
private static String reverse(int num)
{
StringBuffer numstr = new StringBuffer(""+num);
numstr = numstr.reverse();
return new String(numstr);
}
public static int getSum(int num)
{
String numStr = num + "";
int sum = 0;
for (int i = 0; i < numStr.length(); i++)
{
sum = sum+numStr.charAt(i)-'0';
}
return sum;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询