我不知道在我的代码中将String解析为int部分有什么问题。在解析之前,一切看起来都是正确的。
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");
}
}
}
答案 0 :(得分:3)
您没有将String
的归档trim()
存储在任何地方。你可以这样做:
s2 = s2.trim();
int newI = Integer.parseInt(s2);
或
int newI = Integer.parseInt(s2.trim());
答案 1 :(得分:0)
s2 = s2.trim();
更改try块中的这部分代码。
您正在修剪字符串,但没有将其分配给引用它的变量,因为仍然遗漏了空格并且解析此类字符串会引发异常。
答案 2 :(得分:0)
Java对象是不可变的,这意味着它们无法被更改,而Strings是Java中的对象。
您的第s2.trim()
行会返回修剪后的版本,但不会直接修改s2
。但是,您不能将其存储在任何位置,因此当您在下一行解析它时,它将使用未修剪的s2
。
你想要的是s2 = s2.trim()
,它会将裁剪后的版本存回。
答案 3 :(得分:0)
据我所知,你想截断小数。如果是这样,那么你可以找到小数位并对字符串进行子串,然后解析它。
注意:您可能希望在仍然无法解析的字符串中添加一些try-catches。
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
}
答案 4 :(得分:0)
您的代码存在的问题是,当&#39;。&#39;时,您正在脱离for循环。到达角色。
由于您创建了长度为5的ch2
,这意味着最后三个空格为空。当您将其放在带有String s2 = new String(ch2)
的字符串中时,则会在字符串末尾添加三个特殊字符,一个用于ch2
字符数组中的每个空格。
要解决此问题,请将ch2
数组的长度设置为2,或者如果要动态确定长度,请执行&#39; ' in the
String s的索引{{ 1}} s.indexOf(&#39;&#39;)with
&#39;
这可以解决您问题中所述的问题。
答案 5 :(得分:0)
你的ch2数组中有未初始化的字符。您可以在修剪之前将它们设置为空格或使用其他字符串构造函数。例如:
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");
}
}
}