Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: hi! HELP ME!!!!!!!!!! :( :)

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question hi! HELP ME!!!!!!!!!! :( :)

    How to get answer 15 instead of 105 when user entered 10 as a number????? pls help!!!!!!


    package userinputactivity;

    import java.util.Scanner;

    public class UserInputActivity {

    public static void main(String[] args) {

    Scanner name = new Scanner(System.in);

    System.out.println("Please enter a number :");

    int num2 = 5;

    String num = name.next();

    String total = (num + num2);

    System.out.println("Answer is: " +total);
    }

    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,321
    Thanks
    56
    Thanked 2,374 Times in 2,345 Posts

    Default Re: hi! HELP ME!!!!!!!!!! :( :)

    Please explain what the code is supposed to do.

    The + operator does different things depending on the type of the operands it is used with.
    When the operands are numeric, their values are added together: 5 + 10 = 15
    When the operands are Strings, their values are concatenated: "5" + "10" = "510".

    If mixed, the compiler converts the int to a String and concatenates them.
    Last edited by Norm; June 16th, 2012 at 10:50 AM.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Apr 2012
    Posts
    163
    Thanks
    0
    Thanked 27 Times in 27 Posts

    Default Re: hi! HELP ME!!!!!!!!!! :( :)

    In other words, instead of using the Scanner's next() method (which will get a string value), use the nextInt() method to get an int value.