简体   繁体   English

无法将字符串解析为int

[英]Failed to parse a String to int

I don't know what's wrong with parsing the String to an int part in my code. 我不知道将String解析为代码中的int部分有什么问题。 Before the parsing, everything looks correct. 在解析之前,一切看起来都是正确的。

import java.io.IOException;

public class TheWindow {

    public static void main(String[] args) throws IOException{

        String s = "13.16";
        double d = Double.parseDouble(s);
        System.out.println(d);
        char[] ch = s.toCharArray();
        char[] ch2 = new char[s.length()];
        for(int i = 0; i < ch.length; i++){
            if(ch[i] == '.'){
                break;
            }else{
                ch2[i] = ch[i];
            }
        }
        String s2 = new String(ch2);
        System.out.println(s2);
        try{
            s2.trim();
            int newI = Integer.parseInt(s2);
            System.out.println(newI);
        }catch(Exception e){
            System.out.println("Failed");
        }
    }
}

You are not storing the returned String from trim() anywhere. 您不在任何地方存储从trim()返回的String You could either do: 您可以这样做:

s2 = s2.trim();
int newI = Integer.parseInt(s2);

or 要么

int newI = Integer.parseInt(s2.trim());
s2 = s2.trim(); 

change this part of code in the try block. 在try块中更改这部分代码。

You are trimming the string but not assigning it to the variable that refers it due to which the spaces are still left out and parsing such string is throwing an exception. 您正在修剪字符串,但未将其分配给引用该字符串的变量,原因是由于这些空格仍被遗漏,因此解析此类字符串会引发异常。

Java objects are immutable, meaning they can't be changed, and Strings are Objects in Java. Java对象是不可变的,这意味着它们不能更改,而字符串是Java中的对象。

Your line s2.trim() will return the trimmed version, but s2 will not be directly modified. 您的s2.trim()行将返回修剪后的版本,但是s2不会被直接修改。 However, you aren't storing it anywhere, so when you parse it on the next line, it will be with the untrimmed s2 . 但是,您不会将其存储在任何地方,因此当您在下一行对其进行解析时,它将与未修剪的s2

What you want is s2 = s2.trim() , which will store the trimmed version back in. 您想要的是s2 = s2.trim() ,它将s2 = s2.trim()回的版本存储回去。

From what I understand, you want to truncate the decimal. 据我了解,您想截断小数点。 If so, then you can just find the decimal place and substring the string, then parse it. 如果是这样,那么您可以找到小数点后再对字符串进行子字符串化,然后对其进行解析。

Note: You might want to add back in some try-catches for strings that still cannot be parsed. 注意:您可能想在一些try-catching中添加仍无法解析的字符串。

private static int tryParseInt(String str) {
    int decimalIndex = str.indexOf(".");

    if (decimalIndex != -1) {
        return Integer.parseInt(str.substring(0, decimalIndex));
    } else {
        return Integer.parseInt(str);
    }
}

public static void main(String[] args) {
    System.out.println(tryParseInt("13.16")); // 13
}

The problem with your code is that you are breaking out of the for loop when the '.' 代码的问题是,当'。'时,您将退出for循环。 character is reached. 字符已到达。

Since you created ch2 with a length of 5 then this means the last three spaces are null. 由于您创建的ch2的长度为5,因此这意味着最后三个空格为空。 When you put that in a string with String s2 = new String(ch2) then then three special characters are added at the end of the string, one for each empty space in the ch2 character array. 当您将其放入String s2 = new String(ch2)的字符串中时,则会在字符串的末尾添加三个特殊字符,其中一个用于ch2字符数组中的每个空白。

To fix this then set the length of the ch2 array to be two, or if you want to dynamically determine the length, do the index of the ' ' in the String s with s.indexOf('.') and then set the length of the array to one minus the index of ' '. 要解决此问题,然后将ch2数组的长度设置为2,或者如果要动态确定长度,请with s.indexOf('。') ' in the String s中对' ' in the索引, and then set the length of the array to one minus the index of ' ”。

This should fix your problem as stated in your question. 如您的问题所述,这应该可以解决您的问题。

You have uninitialized characters in your ch2 array. 您的ch2数组中有未初始化的字符。 You can set them to space before trimming or use a different string constructor. 您可以在修剪前将它们设置为空格,或使用其他字符串构造函数。 For example: 例如:

        public static void main(String[] args) {

        String s = "13.16";
        double d = Double.parseDouble(s);
        System.out.println(d);
        char[] ch = s.toCharArray();
        char[] ch2 = new char[s.length()];
        int i = 0;
        for(i = 0; i < ch.length; i++){
            if(ch[i] == '.'){
                break;
            }else{
                ch2[i] = ch[i];
            }
        }
        String s2 = new String(ch2, 0, i);
        System.out.println(s2);
        try{
            s2.trim();
            int newI = Integer.parseInt(s2);
            System.out.println(newI);
        }catch(Exception e){
            System.out.println("Failed");
        }
    }

} }

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

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