CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2013
    Posts
    20

    JAva help, need to understand

    Hello everyone, I desperately need someone to help me figure out why the output, listed on the bottom of post, is giving me a result of 220. I need to understand why this is giving me the result of 220 and if someone can help me fix this to where the result is my initials instead of 220. please help!!!!!!!!

    import java.util.Scanner;

    public class UserID {

    public static void main(String args[]) {

    Scanner login = new Scanner(System.in);

    System.out.println("Enter your First Name?.");

    String firstname = login.nextLine();
    char first = firstname.charAt(0);
    System.out.println(first);


    System.out.println( "Enter your complete middle name?.");
    String middlename = login.nextLine();
    char middle = middlename.charAt(0);

    System.out.println(middle);

    System.out.println("Enter your last name?.");

    String lastname = login.nextLine();
    char last = lastname.charAt(0);
    System.out.println(last);
    //String name = (first + middle + last);
    System.out.println( first + middle + last );



    Output:
    Enter your First Name?.
    Daniel
    D
    Enter your complete middle name?.
    Eben
    E
    Enter your last name?.
    Stevens
    S
    220

  2. #2
    Join Date
    May 2009
    Posts
    2,413

    Re: JAva help, need to understand

    Quote Originally Posted by dstevens View Post
    I need to understand why this is giving me the result of 220
    Due to implicit conversion the chars are converted to their Unicode numbers which are 'D'=68, 'E'=69 and 'S'=83. The sum is 220.

    To get the wanted conversion you can give the compiler a hint to nudge it in the right direction, like

    System.out.println("" + first + middle + last );

    Now the compiler will interpret the + operators involved to mean String concatenation rather than integer addition. So the problem was that + is overloaded for both integers and String and you didn't get the implicit conversions you expected. To be very explicit about it you can do,

    System.out.println(Character.toString(first) + Character.toString((middle) + Character.toString(last));

    Now there's no doubt but it's kind of tedious so most people rely on implicit conversion with enougth information to make the compiler do the right thing.
    Last edited by nuzzle; January 19th, 2013 at 02:34 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured