关于 Integer.parseInt() 和强制转换的 Java 初学者问题
因此,当像下面的语句一样进行铸造时:-
int randomNumber=(int) (Math.random()*5)
它会导致随机编号。生成以转换为 int ..
还有一个我刚刚遇到的方法 Integer.parseInt() ,它的作用相同!
即返回一个整数
为什么有两种不同的方法来使值成为 int ?
我还进行了搜索,它说 parseInt() 将字符串作为参数。那么这是否意味着 parseInt() 只能将 String 转换为整数?
那么这个选角怎么样(int)?我们也可以用它来将字符串转换为 int 吗?
抱歉,如果这听起来像一个愚蠢的问题..我只是很困惑并试图理解
帮助?
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..
Also there's this method I just came across Integer.parseInt() which does the same !
i.e return an integer
Why two different ways to make a value an 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 ?
What about this casting then (int) ?? Can we use this to convert a string to an int too ?
sorry if it sounds like a dumb question..I am just confused and trying to understand
Help ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Integer.parseInt 不会做与强制转换相同的事情。
让我们看一下您的第一个示例:
Math.random 返回一个 double,当您将 double 与 int 相乘时,Java 认为结果是 double。因此,表达式 Math.random()*5 的类型为 double。您要做的就是将该值分配给 int 类型的变量。默认情况下,Java 不允许您将 double 值分配给 int 类型的变量,除非您明确告诉编译器可以这样做。基本上,您可以将 double 转换为 int 来告诉编译器,“我知道这个 int 变量不能保存这个 double 值的小数部分,但是没关系,只需截断它即可。”
现在看一下 String 到 int 的转换:
字符串“5”并不能立即转换为整数。与双精度数不同,根据定义,双精度数可以通过删除小数部分来转换为整数,而字符串不能轻松或一致地转换为整数。 “5”、“042”和“1,000”都有整数表示,但像“Hello, World!”之类的东西。没有。因此,不存在将 String 转换为 int 的一阶语言功能。相反,您使用一种方法来解析字符串并返回值。
所以回答你所有的问题:
您必须考虑要转换的值的类型。如果要将基元转换为 int,则可以使用强制转换;如果要转换对象,则需要使用特定于该类型的某种转换方法。
正确的。您不能将任何其他类型传递给 parseInt 方法,否则您将收到编译器错误。
不,转换为 int 仅适用于原始值,并且在 Java 中 String 不是原始值。
Integer.parseInt does not do the same thing as a cast.
Let's take a look at your first example:
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."
Now take a look at the conversion of a String to an int:
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.
So to answer all your questions:
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.
Correct. You cannot pass any other type to the parseInt method or you will get a compiler error.
No, casting to int will only work for primitive values, and in Java a String is not a primitive.
在您的示例中,您将浮点数转换为 int。然而,Integer.parseInt() 从字符串中读取整数值。
In your example, you are casting a floating-point number to an int. Integer.parseInt(), however, reads an integer value from a String.
您只能在兼容类型之间进行转换(我会链接到 JLS,但这对于初学者来说可能太多了)。
转换基本上只是获取一个值并说:“嘿,这个东西以前是双精度数?现在它是整数。所以就这样。”
你不能用字符串来做到这一点,因为它与整数不同。相反,您必须从中解析一个 int ,这实际上比听起来要困难得多。幸运的是,它已经为您实现了,因此您不必担心它是如何工作的。
You can only cast between compatible types (I'd link to the JLS but that might be too much for a beginner question).
Casting is basically just taking a value and saying, "Hey, this thing that was a double? Now it's an int. So there."
You can't do that with a string because it isn't anything like an int. You have to instead parse an 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.
强制转换只能从一种数字类型转换为另一种数字类型。解释字符串(也称为解析)需要通过方法调用来完成。
Casting can only convert from one numeric type to another. Interpreting a string (aka parsing) needs to be done with a method call.
让我们从顶部开始。
是的,这确实给出了 0 到 4 之间的随机整数,但这并不是正确的方法。你看,如果你忘记了括号,即你输入的结果
总是 0,因为强制转换的优先级高于乘法。也就是说,Math.random() 的结果首先被强制转换为整数,该整数始终为 0,然后乘以 5,仍然为 0。
我更喜欢使用 java.util.Random 来生成随机整数。 qv http://java. sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int)。
只能在“兼容类型”之间进行转换。对于基本类型及其包装器(即 int、Integer、long、Long 等),您始终可以在它们之间进行转换,但需要注意的是某些转换会丢失信息。例如,当将 long 转换为 int 时,long 可能包含大于 Integer.MAX_VALUE] 的数字。这种类型转换 Java 基本上是从 C++ 继承来的,而 C++ 又是从 C 继承来的。
至于对象的类型转换,其实更简单。简单地问“这个物体是 X 吗?”如果是这样,那么 (X) o 有意义并且具有静态类型 X。如果 o 不是 X 并且您无论如何尝试进行强制转换,您将得到一个 ClassCastException,表示 o 的动态(运行时)类型与 X 不兼容。这将当您了解对象的静态类型和动态(运行时)类型之间的差异时,可能会更有意义。
Let's start from the top.
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
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.
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).
Casting can only be done between "compatible types". For primitive types and their wrappers (i.e. int, Integer, long, Long, &c.) you can always cast 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.
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.
以下代码将 String 转换为 int,无需任何方法
输出“3256” --> 3256
Following code convert String to int without any methods
Output "3256" --> 3256
Parse()方法可用的格式有很多种,Integer类有方法ParseInt(),它是一个静态方法,我们通过Integer.ParseInt()来调用这个方法
类似的 Double 类具有 ParseDouble(),我们将其称为 Double.ParseDouble()。
更通用的方法是 XXXX.ParseXXXX()
该方法的主要用途是将任何 Object 转换为 Primitive。
这里你可以提出一个问题,为什么我们需要转换成基元?
答案是,我们知道基元存储在堆栈区域,对象存储在堆区域,如果您不想浪费堆内存,可以将对象转换为基元。
另一件事是,在访问任何对象时可能会产生开销。
最好用作基元。
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.