如何拆分成整数使用Java数组? [英] How to split an Integer into an Array using Java?
问题描述
我道歉,如果这已经被问过,但我无法找到经过一番搜索大量确凿的答案,所以我想我会问这里。我是一个初学者到Java(编码,在一般情况),并编写一个程序,需要用户输入3位数字,并增加了这三个数字受命。
注:我不能循环使用此任务,三个数字必须一次全部输入。
字符串myInput;
myInput =
JOptionPane.showInputDialog(NULL,你好,欢迎到ThreeDigit程序。
+\\ n请输入以下三个数字\\ nThreeDigit将增加这三个数字并显示它们的总和。);
INT threedigitinput;
threedigitinput =的Integer.parseInt(myInput);
有多种方式,其中之一将是...
字符串SS [] =123.split();
INT I =
的Integer.parseInt(β[0])+
的Integer.parseInt(β[1])+
的Integer.parseInt(β[2]);
的System.out.println(ⅰ);
另一个是...
一个String =123;
INT I =
Character.getNumericValue(s.charAt(0))+
Character.getNumericValue(s.charAt(1))+
Character.getNumericValue(s.charAt(2));
的System.out.println(ⅰ);
还有一个是...
一个String =123;
INT I =
s.charAt(0)+
s.charAt(1)+
s.charAt(2) -
(3 * 48);
的System.out.println(ⅰ);
但硬编码的3个数字是不是超出了简单的情况下非常有用的。因此,如何递归??
公共静态INT addDigis(String s)将{
如果(s.length()== 1)
返回s.charAt(0) - 48;
返回s.charAt(0) - 48±addDigis(s.substring(1,s.length()));
}
每个示例输出:6
块引用>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
这篇关于如何拆分成整数使用Java数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!