Menu

Java: incompatible types: String cannot be converted to int, and how to fix it
📰

Java: incompatible types: String cannot be converted to int, and how to fix it

DEV Community: java·Craftstack Academy·about 21 hours ago
#QZyWb2Tc
#devtojava#devto#dev#java#string
Reading 0:00
15s threshold

You press compile, and before your program even starts, Java refuses:

Main.java:7: error: incompatible types: String cannot be converted to int int hours = scanner.nextLine(); ^ 1 error

Enter fullscreen mode

Exit fullscreen mode

The good news: this is a compile error. Java found the problem before running anything, and it tells you the exact file, line and spot. Here's what it means, the usual causes, how to fix each one, and the related errors you're likely to meet next.

What the error means

Main.java:7 : the file and the line number.

incompatible types : you put a value of one type into a place meant for another type.

String cannot be converted to int : the value is a String (text), and the place, here the variable hours , is an int (a whole number). Java won't turn one into the other on its own.

The ^ mark shows where Java noticed it: at the end of scanner.nextLine() , the expression that produced the text.

Java checks types very strictly.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.