简体   繁体   English

无法解析Java中字符串中的字符

[英]Cannot parse characters from string in java

import java.util.Scanner;

public class Out {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        String[] arr = new String[n];
        int result = 0;
        for(int i = 0; i < n; i++) {
            arr[i] = input.next();
            System.out.println(arr[i]);
            System.out.println(Double.parseDouble(arr[i].replace(Character.toString(arr[i].charAt(arr[i].length() - 1)), "")));
            System.out.println(Double.parseDouble(Character.toString(arr[i].charAt(arr[i].length() - 1))));
            result += Math.pow(Double.parseDouble(arr[i].replace(Character.toString(arr[i].charAt(arr[i].length() - 1)), "")), Double.parseDouble(Character.toString(arr[i].charAt(arr[i].length() - 1))));


        }
        System.out.println(result);

    }

}

This code is supposed to get a string (eg 567) and raise 56 to the power of 7. It is NOT working only for the case when I have 212. I know it is very easy with arr[i]/10 and arr[i]%10. 该代码应该获得一个字符串(例如567)并将56提高到7的幂。它仅在我有212的情况下不起作用。我知道使用arr [i] / 10和arr [非常容易I]%10。 But I cannot understand the behavior here. 但是我无法理解这里的行为。 I wanted to know why this solution is not working. 我想知道为什么这个解决方案不起作用。 Thank you! 谢谢!

String.replace will not work here. String.replace在这里不起作用。 This function replaces all occurrences of the character in the string. 此函数替换字符串中所有出现的字符。

So for a number like 212, "212".replace("2", "") will result in "1". 因此,对于像212这样的数字,“ 212” .replace(“ 2”,“”)将得到“ 1”。

See https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-char-char- 参见https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-char-char-

Consider using substring: 考虑使用子字符串:

String s = "212"
System.out.println(s.substring(0, s.length() - 1)); //prints 21
System.out.println(s.substring(s.length()-1)); //prints 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM