-2

Okay so I want to create a for loop that assigns variables with each increment of i. This is what I have, but it doesn't work due to a type mismatch:

int i;
String d;
for(i = 5; i > 0; i--){
String.valueOf(i);
d = i;
d = reader.readLine();
System.out.println(d);
}

So the error that I get right now is "type mismatch" when setting d = i. Obviously I get the error due to d not being an int but a String, but I thought String.valueOf(i) was supposed to convert i to a String? I must have misunderstood this. What am I doing wrong in this or what is another way to do this?

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84

3 Answers3

2

String.valueOf(i) returns a string representation of i. You're throwing that away, by executing this as a statement.

Did you intend d = String.valueOf(i);, perhaps?

(Just a guess. Since you promptly overwrite d in the following line, I'm not sure what you're actually trying to accomplish.)

keshlam
  • 7,931
  • 2
  • 19
  • 33
  • This actually explains the mistake in contrast with the other answers that just provide an alternative solution. – Menno Jan 17 '14 at 20:35
1

You can implicitly convert i to a String by doing "" + i

int i;
String d;
for(i = 5; i > 0; i--){
   d = "" + i;
   System.out.println(d);
}
Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
0

I'm not sure what you're trying to do. If you want to just output

5 4 3 2 1

then try:

int i;
String d;
for(i = 5; i > 0; i--){
d = String.valueOf(i);
System.out.println(d);
System.out.println( " " );
}