java split 整数,如何拆分成整数使用Java数组?

I apologise if this has already been asked before, but I was unable to find a conclusive answer after some extensive searching, so I thought I would ask here. I am a beginner to Java (to coding, in general) and was tasked with writing a program that takes a user-inputted 3 digit number, and adds those three digits.

Note: I cannot use loops for this task, and the three digits must all be inputted at once.

String myInput;

myInput =

JOptionPane.showInputDialog(null,"Hello, and welcome to the ThreeDigit program. "

+ "\nPlease input a three digit number below. \nThreeDigit will add those three numbers and display their sum.");

int threedigitinput;

threedigitinput = Integer.parseInt(myInput);

解决方案

There are a number of ways, one of which would be...

String ss[] = "123".split("");

int i =

Integer.parseInt(ss[0]) +

Integer.parseInt(ss[1]) +

Integer.parseInt(ss[2]);

System.out.println(i);

another would be...

String s = "123";

int i =

Character.getNumericValue(s.charAt(0)) +

Character.getNumericValue(s.charAt(1)) +

Character.getNumericValue(s.charAt(2));

System.out.println(i);

and still another would be...

String s = "123";

int i =

s.charAt(0) +

s.charAt(1) +

s.charAt(2) -

(3 * 48);

System.out.println(i);

BUT hard coding for 3 numbers isn't very useful beyond this simple case. So how about recursion??

public static int addDigis(String s) {

if(s.length() == 1)

return s.charAt(0) - 48;

return s.charAt(0) - 48 + addDigis(s.substring(1, s.length()));

}

Output for each example: 6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值