关于 Integer.parseInt() 和转换的初学者 Java 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2875544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Beginner Java Question about Integer.parseInt() and casting
提问by Serenity
so when casting like in the statement below :-
所以当像下面的声明一样铸造时:-
int randomNumber=(int) (Math.random()*5)
it causes the random no. generated to get converted into an int..
它导致随机编号。生成以转换为 int ..
Also there's this method I just came across Integer.parseInt() which does the same !
还有这个方法我刚遇到 Integer.parseInt() 它做同样的事情!
i.e return an integer
即返回一个整数
Why two different ways to make a value an int ?
为什么有两种不同的方法使值成为 int ?
Also I made a search and it says parseInt() takes string as an argument.. So does this mean that parseInt() is ONLY to convert String into integer ?
我也做了一个搜索,它说 parseInt() 将字符串作为参数..那么这是否意味着 parseInt() 只能将 String 转换为 integer ?
What about this casting then (int) ?? Can we use this to convert a string to an int too ?
那么这个铸造呢 (int) ?? 我们也可以使用它将字符串转换为 int 吗?
sorry if it sounds like a dumb question..I am just confused and trying to understand
对不起,如果这听起来像一个愚蠢的问题..我只是困惑并试图理解
Help ?
帮助 ?
采纳答案by Mike Deck
Integer.parseInt does not do the same thing as a cast.
Integer.parseInt 不做与演员相同的事情。
Let's take a look at your first example:
让我们来看看你的第一个例子:
int randomNumber=(int) (Math.random()*5)
Math.random returns a double, and when you multiply a double by an int Java considers the result to be a double. Thus the expression Math.random()*5 has a type of double. What you're trying to do is assign that value to a variable of type int. By default Java will not allow you to assign a double value to a variable of type int without your explicitly telling the compiler that it's ok to do so. Basically you can think of casting a double to an int as telling the compiler, "I know this int variable can't hold the decimal part of this double value, but that's ok, just truncate it."
Math.random 返回双精度值,当您将双精度值乘以整数时,Java 认为结果为双精度值。因此,表达式 Math.random()*5 具有 double 类型。您要做的是将该值分配给 int 类型的变量。默认情况下,Java 不允许您在没有明确告诉编译器可以这样做的情况下将 double 值分配给 int 类型的变量。基本上,您可以认为将 double 转换为 int 就像告诉编译器,“我知道这个 int 变量不能保存这个 double 值的小数部分,但没关系,只需将其截断即可。”
Now take a look at the conversion of a String to an int:
现在看一下 String 到 int 的转换:
int value = Integer.parseInt("5");
The string "5" is not immediately convertible to an integer. Unlike doubles, which by definition can be converted to an integer by dropping the decimal part, Strings can't be easily or consistently converted to an int. "5", "042", and "1,000" all have integer representations, but something like "Hello, World!" does not. Because of this there is no first order language feature for converting a String to an int. Instead, you use a method to parse the String and return the value.
字符串“5”不能立即转换为整数。与根据定义可以通过删除小数部分将双精度数转换为整数的双精度数不同,字符串不能轻松或一致地转换为整数。“5”、“042”和“1,000”都有整数表示,但类似于“Hello, World!” 才不是。因此,没有将 String 转换为 int 的一阶语言功能。相反,您使用一种方法来解析字符串并返回值。
So to answer all your questions:
所以要回答你所有的问题:
Why two different ways to make a value an int ?
为什么有两种不同的方法使值成为 int ?
You have to take into account what the type of the value you are converting is. If you're converting a primitive to an int you can use a cast, if you're converting an Object you'll need to use some sort of conversion method specific to that type.
您必须考虑要转换的值的类型。如果要将原始类型转换为 int,则可以使用强制转换,如果要转换 Object,则需要使用某种特定于该类型的转换方法。
Also I made a search and it says parseInt() takes string as an argument.. So does this mean that parseInt() is ONLY to convert String into integer ?
我也做了一个搜索,它说 parseInt() 将字符串作为参数..那么这是否意味着 parseInt() 只能将 String 转换为 integer ?
Correct. You cannot pass any other type to the parseInt method or you will get a compiler error.
正确的。您不能将任何其他类型传递给 parseInt 方法,否则您将收到编译器错误。
What about this casting then (int) ?? Can we use this to convert a string to an int too ?
那么这个铸造呢 (int) ?? 我们也可以使用它将字符串转换为 int 吗?
No, casting to int will only work for primitive values, and in Java a String is not a primitive.
不,转换为 int 仅适用于原始值,并且在 Java 中 String 不是原始值。
回答by Carl Manaster
In your example, you are casting a floating-point number to an int. Integer.parseInt(), however, reads an integer value from a String.
在您的示例中,您将浮点数转换为 int。然而,Integer.parseInt() 从字符串中读取一个整数值。
回答by Paul Tomblin
Casting can only convert from one numeric type to another. Interpreting a string (aka parsing) needs to be done with a method call.
强制转换只能从一种数字类型转换为另一种数字类型。解释字符串(又名解析)需要通过方法调用来完成。
回答by Michael Myers
You can only cast between compatible types (I'd link to the JLS but that might be too much for a beginner question).
您只能在兼容类型之间进行转换(我会链接到 JLS,但这对于初学者问题来说可能太多了)。
Casting is basically just taking a value and saying, "Hey, this thing that was a double? Now it's an int. So there."
Casting 基本上只是取一个值然后说,“嘿,这个是 double 的东西?现在它是一个 int。所以就这样。”
You can't do that with a string because it isn't anything like an int. You have to instead parsean int out of it, which is actually a lot harder than it sounds. Fortunately, it's already implemented for you so you don't have to worry about how it works.
你不能用字符串来做这件事,因为它不像 int。相反,您必须从中解析出一个 int,这实际上比听起来要困难得多。幸运的是,它已经为您实现,因此您不必担心它是如何工作的。
回答by kahen
Let's start from the top.
让我们从顶部开始。
int randomNumber=(int) (Math.random()*5);
Yes, this does indeed give a random integer between 0 and 4, but this is very much not the proper way of doing this. You see, if you forget a parenthesis, i.e. you type
是的,这确实给出了 0 到 4 之间的随机整数,但这非常不是这样做的正确方法。你看,如果你忘记了括号,即你输入
int notSoRandomNumber=(int) Math.random()*5;
you'll always get 0 because casting has higher precedence than multiplication. That is to say the result of Math.random() is first coerced into an integer, which will always be 0 and then it's multiplied by 5, which is still 0.
你总是会得到 0,因为转换比乘法有更高的优先级。也就是说Math.random()的结果首先被强制为一个整数,这个整数永远是0,然后乘以5,仍然是0。
I'd favour using java.util.Random for generating random integers. q.v. http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int).
我更喜欢使用 java.util.Random 来生成随机整数。qv http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int)。
Casting can only be done between "compatible types". For primitive types and their wrappers (i.e. int, Integer, long, Long, &c.) you can alwayscast between them with the caveat that some conversions lose information. e.g. when casting a long to an int, the long may contain a number larger than Integer.MAX_VALUE]. This kind of casting Java basically got from C++ which it in turn got from C.
只能在“兼容类型”之间进行转换。对于原始类型及其包装器(即 int、Integer、long、Long 等),您始终可以在它们之间进行转换,但需要注意的是某些转换会丢失信息。例如,当将 long 转换为 int 时,long 可能包含一个大于 Integer.MAX_VALUE] 的数字。这种转换 Java 基本上来自 C++,而它又来自 C。
As for casting objects, it's actually simpler. Simply ask "is this object, o, an X?" If so then (X) o makes sense and has static type X. If o is not an X and you try to cast anyway, you'll get a ClassCastException signifying that o's dynamic (runtime) type is not compatible with X. This will probably make a lot more sense later when you get the difference between the static and the dynamic (runtime) type of objects.
至于铸造对象,其实更简单。只需问“这个物体,哦,是 X 吗?” 如果是,那么 (X) o 有意义并且具有静态类型 X。如果 o 不是 X 并且您无论如何都尝试进行强制转换,您将得到 ClassCastException 表示 o 的动态(运行时)类型与 X 不兼容。这将稍后当您了解静态和动态(运行时)类型的对象之间的区别时,可能会更有意义。
回答by sunil waghole
Following code convert String to int without any methods
以下代码无需任何方法即可将 String 转换为 int
public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0'; // '0'=48 zeroAscii=48
for(int i=0;i<ch.length;i++){
int tmpAscii = (int)ch[i]; // for 0 ch[i]=3,3=51, tempAscii=51
// (0*10)+(51-48)
// 0 +3
// 3
// sum=3
// for 1 ch[i]=2,2=50, tempAscii=50
sum = (sum*10)+(tmpAscii-zeroAscii); // 0 +(51-48)=3 sum=3
// (3*10)=30+(50-48)
// 30 + 2
// sum=32
// for 2 ch[i]=5, 5=53 tempAscii=53
// (32*10)+(53-48)
// 320 + 5
// 325
// sum=325
// for 3 ch[i]=6,6=54, tempAscii=54
// (325*10)+(54-48)
// 3250 +6
// 3256
// sum=3256
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
}
}
Output "3256" --> 3256
输出“3256”--> 3256
回答by Naga Venkatesh Gavini
Parse() method is available is many formats, Integer class having the method ParseInt() which is a static method, we to call this method by Integer.ParseInt()
Similarly Double class having ParseDouble()and we call it as Double.ParseDouble().
The more Generic way is XXXX.ParseXXXX()
The main use of this Method is to convert any Object into a Primitive.
And here you can raise a question why we need to convert into Primitives? The answer is, we know that primitives are stored in stack area and objects are stored in Heap area, and you doesn't want to waste the Heap Memory and you can convert an Object into a Primitive.
And the other thing, while accessing any Object there may be Overhead. It is better to use as a Primitive.
Parse() 方法可用的格式有很多,Integer 类有 ParseInt() 方法,它是一个静态方法,我们通过 Integer.ParseInt() 来调用这个方法
同样具有 ParseDouble() 的 Double 类,我们称之为 Double.ParseDouble()。
更通用的方式是 XXXX.ParseXXXX()
此方法的主要用途是将任何 Object 转换为 Primitive。
在这里你可以提出一个问题,为什么我们需要转换成 Primitives?答案是,我们知道primitives存放在stack area,objects存放在Heap area,你不想浪费Heap Memory,你可以把Object转换成Primitive。
另一件事,在访问任何对象时可能会有开销。最好用作 Primitive。