![](/img/trans.png)
[英]Convert a text to integer, increment and reconvert as text, any easier way?
[英]Is there any easier way to set integer for string characters?
我正在制作将随机字符串转换为数字的方法。 但是我想知道是否有更简单的方法可以做到这一点:
package codec; import javax.swing.JFrame; public final class Codec extends JFrame { public static void main(String[] args) { String x = "qwertyuiopasdfghjkl"; int a = x.charAt(1); int b = x.charAt(2); int c = x.charAt(3); int d = x.charAt(4); int e = x.charAt(5); int f = x.charAt(6); int g = x.charAt(7); int h = x.charAt(8); int i = x.charAt(9); int j = x.charAt(10); int k = x.charAt(11); int l = x.charAt(12); int m = x.charAt(13); int n = x.charAt(14); int o = x.charAt(15); int p = x.charAt(16); int q = x.charAt(17); int r = x.charAt(18); System.out.println(a*b+c+d*e+f+g*h+i+j*k+l*m+n*o+p+q*r); } }
它给我“ 81782”,我可以简单地更改数字和计算。 我没有写太多Java,所以我真的是个初学者。 用循环执行此操作是否合理:
for (int i = 1; i < x.length() ; i++){ //code }
也许这可以帮助您。 另外,请注意,字符串从索引0而不是1开始。因此,您的“ a”是符号“ w”。
public static void main(String[] args) {
String x = "qwertyuiopasdfghjkl";
Map<Character, Integer> charMap = new HashMap<>();
char c = 'a';
for (int i = 1; i < x.length(); i++) {
charMap.put(c++, (int) x.charAt(i));
}
System.out.println(charMap.get('a') * charMap.get('b')
+ charMap.get('c')
+ charMap.get('d') * charMap.get('e')
+ charMap.get('f')
+ charMap.get('g') * charMap.get('h')
+ charMap.get('i')
+ charMap.get('j') * charMap.get('k')
+ charMap.get('l') * charMap.get('m')
+ charMap.get('n') * charMap.get('o')
+ charMap.get('p')
+ charMap.get('q') * charMap.get('r'));
}
这是使用循环的代码
String afd = "234567890";
int sum=0;
for(int ij=0;ij<afd.length();ij+=2)
{
sum = sum + (afd.charAt(ij)*afd.charAt(ij+1));
}
System.out.println(sum);
希望我的代码在这方面对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.