There is an error showing that after using nextInt there is an error showing that it can not be converted to string
This is the code I have written
import java.util.*;
public class practics{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
String number=scanner.nextInt();
System.out.println(number);
}
}
[{
"resource": "/c:/Users/hpmsc/OneDrive/Desktop/Java Programming Language/LearningJava/PracticeJava/src/practics.java",
"owner": "_generated_diagnostic_collection_name_#2",
"code": "16777233",
"severity": 8,
"message": "Type mismatch: cannot convert from int to String",
"source": "Java",
"startLineNumber": 5,
"startColumn": 23,
"endLineNumber": 5,
"endColumn": 40
}]NIL
Harshita Kadiyan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
The method nextInt
from Scanner
returns an int
type so you will need to change your number variable from String number
to int number
and it should work just fine.
For reference here is the javadoc for the method.
Anthony Lofton is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
An int
is not a String
. And can’t be implicitly converted into one. But you have at least two ways to solve this issue.
Option 1
Make it an int
.
int number=scanner.nextInt(); // An `int` can be printed
Option 2
Explicitly convert the int
into a String
. Like,
String number=String.valueOf(scanner.nextInt());
You’re using nextInt
method from Scanner that returns an int
. You could either change the type of number from String
to int
or you could use the nextLine
method that returns a String
value.
fatrifatrifat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.