• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4424
  • Last Modified:

Can't convert java.lang.String to char.

Hi
I wonder if any body could help me.
Please have a look on the following code:-

import java.rmi.*;
import java.io.*;


public class RoutingClient
{
    public static void main(String[] args)
    {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        try
        {
            Routing obj = (Routing) Naming.lookup("//localhost/Router");

          if ((args.length < 2)|| (args.length >2))
      {              {

System.out.println("usage: java httpc servername port page.html");
System.out.println("example: java httpc www.yahoo.com 80 index.html");
                         return;
                  }
                     //int lineno = args[0];
                     int lineno = Integer.parseInt(args[0]);
                     char code = args[1];
obj.addRoute(lineno,code);

}
}

there is an error on line <char code =args[1]

Error given by compiler is:-

 Incompatible type for declaration. Can't convert java.lang.String to char. char code = args[1];

How to convert String in to char
Thank YOU
0
Rafi-muqaddar
Asked:
Rafi-muqaddar
  • 2
1 Solution
 
venkateshwarrCommented:

String s = args[1];
char[] chars = s.toCharArray();
char code= chars[0];
0
 
VenabiliCommented:
char code = args[1].charAt(0);
0
 
VenabiliCommented:
Oops - did not see venkateshwarr's comment
So... you already have two valid answers.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> char code = args[1];

What if args[1] has more than one character? Do you want to omit the other characters? If so, then the above code is fine, otherwise, you can try:

if ( args[1].length > 1 )
  System.out.println ( "Invalid argument. " ) ;
else
  code = args[1].charAt ( 0 ) ;
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now