• Post Reply Bookmark Topic Watch Topic
  • New Topic

why does one work and not the other?  RSS feed

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String date = "0182";

String newYear = "19"+date.charAt(2)+date.charAt(3);

THE ABOVE WORKS FINE. NO PROBLEMS.

But when I try:

String newMonth = date.charAt(0)+date.charAt(1);

I get the following compilation error:


C:\java\PoliceDatabase>javac VehicleRecord.java
VehicleRecord.java:342: incompatible types
found : int
required: java.lang.String
String newMonth = date.charAt(0)+date.charAt(1);
^
1 error

Am I missing something here?
 
K Riaz
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cast to string.

Try

String newMonth = "" + date.charAt(0)+date.charAt(1);
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that chars are integral values (they are really the Unicode value for whatever character they represent). So the plus operator is performing addition, not concatenation. For example:

Will not compile, but:

Will compile, c being whaterver the integral value of a plus b is.
[ April 14, 2005: Message edited by: Paul Sturrock ]
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many thanks for your quick responses.

My code was changed to the following:

int inputMonth = date.charAt(pos1) + date.charAt(pos2);
//change int inputMonth to String
String newInputMonth = Integer.toString(inputMonth);
System.out.println("inputMonth is: "+newInputMonth);

And it worked like a dream!

Again, many thanks!
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I have had a little play now.

I have my date as a String. i.e. 0579



This works successfully.

But I still want to try and use the toString( ) and valueOf and String Buffer.

So far I have been unsuccessful and don't know why?



The output is as follows:
Validating Registration Date: 0579
VALIDATING YEAR
INVALID REGISTRATION DATE YEAR.
Registration Year successfully validated
VALIDATING MONTH
newDate is: 05
valueOf: test3 = 101
toString is : 101
char1 is NOW:

Finished Validation

I thought valueOf would be 05 now 101 and toString would be 05 not 101.
I also got a result of char1 with nothing. Why?
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!