{{1}}
我不确定这会导致异常的原因。谁能解释一下?非常肯定因为String类型的int,但想确保。
答案 0 :(得分:2)
是的,因为类型转换,你是对的。如果你需要将String转换为int使用下面的代码
Integer.parseInt("3");
答案 1 :(得分:1)
答案 2 :(得分:1)
使用此
Integer.parseInt("3");
或
async function fn1 () {
console.log(1);
await fn2();
console.log(3);
};
async function fn2 () {
console.log(2);
};
async function makeExectionOrder(){ // move the blocks into asynch function
await fn1(); // make synchrounous call
new Promise((resolve, reject) => {
console.log(4)
resolve()
}).then(() => {
console.log(5)
})
}
makeExectionOrder()
答案 3 :(得分:0)
在Java中,每当您尝试将实体的类型更改为另一个实体时,这两种类型都应该有一些关系。就像你试图将sub class
对象关联到super class
一样,它会顺利运行。但是,如果您尝试将Person object
与Lion object
进行比较,那么这种比较意味着更少,同样是投射中的逻辑。我们不能将Person对象强制转换为Lion对象。
在你的代码中bob
是String类型,你试图将它强制转换为int
,而在Java中,String和Integer没有任何关系。这就是为什么Java抛出Exception,Class Cast Exception
我想,当比较不同类型的对象时会引发这种情况。
但Integer类中的parseInt(String arg)
方法提供了将数字String转换为Integer的选项,因为该参数是符合Java标准的合格Integer。
示例: -
String numericString = "1234";
int numberConverted = Integer.parseInt(numericString);
System.out.println(numberConverted);
您也可以尝试使用这些方法,在使用此方法之前告诉您注意事项
int numberConverted = Integer.parseInt("1234r");
int numberConverted = Integer.parseInt("1234.56");
int numberConverted = Integer.parseInt("11111111111111111111111111111");
答案 4 :(得分:0)
您无法将String转换为Integer。变化:
System.out.println((int)bob2);
为:
System.out.println(Integer.parseInt(bob2));
它会根据Integer
变量提供的String
创建bob2
值。如果您想要存储原始int
而不是int
,也可以创建对Integer
变量的引用:
int intBob2 = Integer.parseInt(bob2);