I think that real problem here1 is that you don't have a clear understanding of what a Scanner
does.
A Scanner
reads characters from a stream (for example System.in
) and turns them into various kinds of values; e.g. integers, floating point numbers, strings and so on. The basic model is:
- call
hasNextXXX
to test if there is a XXX
to read.
- call
nextXXX
to read a XXX
.
So you are trying to get a name of a car manufacturer from the Scanner
. Assuming that car manufacturer names don't have spaces in them, what you are reading is a white-space delimited token. The method for reading a token is Scanner::next
. It returns the token as a String
with any leading or trailing whitespace removed.
Aside: String::nextLine
would also work, except that it returns the complete line with all white space entered by the user before or after the name2. If the user enters (for example) Ford
with a space after it, then that won't match the value in your car
list. To deal with that, you would need to do something like this:
String str = sc.nextLine().trim(); // 'trim' removes leading and
// trailing whitespace; e.g. SP,
// TAB, CR and NL characters.
Once you have the name as a String
, you should String::equals
to compare it against other strings. Comparing strings using ==
is incorrect in nearly all circumstances; see How do I compare strings in Java?
For a deeper understanding of Scanner
, I recommend that you take the time to read the javadocs.
Your code doesn't do the above. Instead, it reads a line (i.e. str = sc.nextLine()
) and doesn't use it. Then it uses ==
to test if the Scanner
is equal to each String
in your list. That fails, because a Scanner
is not a String
.
Aside: in Java, ==
for a reference type (i.e. for objects) means "is this the same object".
1 - The other possibility is that you didn't read the code that you had written carefully enough.
2 - ... apart from the line separator sequence; i.e. CR, NL or CR + NL. This is removed automatically by nextLine
: refer to the javadocs for more details.