您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页java split 整数,如何拆分成整数使用Java数组?

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务