我正在尝试做一些程序并需要一些帮助。例如,我在文本框中输入了这个数字:00669253,然后对于每个数字,我想将它与数字87654321相乘,例如
(0x8)+(0x7)+(6x6)....等等然后得到所有数字的总和并做一个11的mod。我怎么能这样做?
感谢您的帮助。
答案 0 :(得分:6)
您可以先将数字转换为String
,然后就可以这样做:
String no1="00669253";
String no2="87654321";
int sum=0;
for(int i=0;i<no1.length();i++){
sum+=Integer.parseInt(""+no1.charAt(i))*Integer.parseInt(""+no2.charAt(i));
}
之后,您可以对sum
答案 1 :(得分:0)
试试这个,
public class Dummy {
public static void main(String[] args) {
String s = "112211";
String s2 = "010101";
char[] sDummy = s.toCharArray();
char[] s2Dummy = s2.toCharArray();
int sum = 0;
for (int i = 0; i < sDummy.length; i++) {
System.out.println("multiplying..." + sDummy[i] + "with " + s2Dummy[i] + "and adding prev sum " + sum + " to it");
sum = sum + (Integer.parseInt(sDummy[i] + "") * Integer.parseInt(s2Dummy[i] + ""));
}
sum = sum % 11;
System.out.println("sum with mod is = " + sum);
}
}
如果两个字符串的长度不同,您需要添加一些检查
答案 2 :(得分:0)
你可以尝试这样的事情:
public class TestMult {
public static void main(String[] args) {
String first = "00669253";
String second = "87654321";
long sum = 0L;
if (first.length() == second.length()) {
for (int i = 0; i < first.length(); i++) {
int firstInt = Character.getNumericValue(first.charAt(i));
int secondInt = Character.getNumericValue(second.charAt(i));
sum += firstInt * secondInt;
}
System.out.println("result: " + sum % 11);
} else {
System.err.println("lengths are not equal.");
}
}
}
答案 3 :(得分:-1)
试试这个,
String inputValue = "00669253";
String multipleValue="87654321";
int result = 0;
for (int i = 0; i < inputValue.length(); i++)
{
result += Integer.parseInt(Character.toString(inputValue.charAt(i))) *
Integer.parseInt(Character.toString(multipleValue.charAt(i)));
}