Results 1 to 5 of 5
  1. #1
    guisome is offline Member
    Join Date
    Feb 2011
    Posts
    7
    Rep Power
    0

    Default Basic Scanner API

    This simple program is printing "input 2" even if you type "yes". Why?
    I know it's very basic, but I started reading some java tutorials about 2 days ago so I don't know much about it.

    import java.util.Scanner;

    class test {

    public static void main(String[] args) {
    System.out.println("Input something");
    Scanner output = new Scanner(System.in);
    String anw = output.nextLine();
    if ( anw == "yes" )
    System.out.println("input 1");
    else
    System.out.println("input 2");


    }
    }
    Last edited by guisome; 02-03-2011 at 12:22 AM.

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Never compare Strings or any other object with == use the equals method instead.

    Never say never. Ok there are some occassions when you do need to use == but when it comes to Strings and you want to compare contents then use the equals method.

  3. #3
    guisome is offline Member
    Join Date
    Feb 2011
    Posts
    7
    Rep Power
    0

    Default

    Using the "equals" method the java points out :

    test:java:9: incompatible types
    found: java.lang.String
    required: boolean
    if ( anw = "yes" )

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    You didn't use the equals method. All you did is delete one = sign. That changes it from a comparison of equality to an assignment. Do you know what a method is and how to call it?

  5. #5
    guisome is offline Member
    Join Date
    Feb 2011
    Posts
    7
    Rep Power
    0

    Default

    I didn't know what was that, but found a tutorial on a website, the program works.

    if (anw.equals("yes"))
    Thanks for answering the thread.
    Last edited by guisome; 02-03-2011 at 01:03 AM.

Similar Threads

  1. Need some basic help
    By backdown in forum New To Java
    Replies: 29
    Last Post: 01-20-2011, 04:06 AM
  2. Basic GUI help
    By vahshir in forum New To Java
    Replies: 5
    Last Post: 10-11-2010, 01:33 AM
  3. Need really basic help!
    By anthonyalaan in forum New To Java
    Replies: 9
    Last Post: 09-12-2010, 01:43 PM
  4. Basic Help
    By robjames in forum New To Java
    Replies: 3
    Last Post: 02-09-2009, 02:58 AM
  5. Need some really basic help
    By Mayur in forum New To Java
    Replies: 6
    Last Post: 01-24-2009, 06:00 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
  •