Reputation: 97
I'm trying to write a code to get given number of repeated times of a input string.
Not written too much code, but here is my code:
public class MultipleCopiesString {
public static void StringCopy(String inp, Integer num) {
for (int i = 0; i < num; i++){
}
}
}
I'm getting error in for loop (i < num)
, I want to know why its coming and how it can be resolved.
Java version is 1.8
and creating code on eclipse
.
Upvotes: 0
Views: 13079
Reputation: 140525
Your problem is of a different nature.
I just put down your code in my eclipse NEON (which uses Java8). And your code compiles fine; not showing any problems.
Because Java is smart enough (by now) to understand that you want to compare two int values. It turns the Integer
num argument into a primitive type int
implicitly. (that is called auto-boxing resp. un-boxing).
So the answer is most likely: you are using an outdated version of eclipse.
Meaning: eclipse has its own Java compiler. Therefore the version of the JRE/JDK you are working with isn't that important when talking about compiler errors given to you. Because those messages come from the built-in eclipse Java compiler.
And when that eclipse Java compiler tells you that Integer can not be converted to int; then the possible explanations are:
Long story short: check your version of eclipse; when it is outdated - turn to eclipse.org, and install the latest version of eclipse. If you are using a recent version of eclipse, check your workspace/project settings.
Upvotes: 7
Reputation: 390
You cannot compare an Integer
data type with an int
data type. This is not valid.
You may rewrite your code as described below:
public class MultipleCopiesString {
public static void StringCopy(String inp, int num) {
for (int i=0; i < num;i++){
}
}
}
Upvotes: 1
Reputation: 722
Try this :
public class MultipleCopiesString {
public static void stringCopy(String inp, int num) {
for (int i=0; i < num;i++){
}
}
}
Or if you want to use Integer :
public class MultipleCopiesString {
public static void stringCopy(String inp, Integer num) {
for (int i=0; i < num.intValue();i++){
}
}
}
In Java the 'int' type is a primitive , whereas the 'Integer' type is an object, meaning you cannot use it like you would use a simple int.
Upvotes: 2
Reputation: 191
2 solutions :
intValue()
method of the Integer class like so : num.intValue()Upvotes: 3